Command line stdout to array in nodejs

2019-09-07 03:27发布

问题:

I am trying to write a node.js application to interface with docker command line tool. My current code is as below:

#!/usr/bin/env node

var child_process = require('child_process');

child_process.exec('docker ps -a', function(error, stdout, stderr){
    console.log(stdout);
});

I get a sample output as below: safwan@ubuntu:~/node$ ./cmd-docker.js

CONTAINER ID        IMAGE               COMMAND                  CREATED             STATUS                     PORTS                                                  NAMES
e855320e9547        wadmiraal/drupal    "/bin/sh -c 'exec sup"   2 weeks ago         Exited (137) 12 days ago   3306/tcp, 0.0.0.0:8022->22/tcp, 0.0.0.0:8080->80/tcp   stupefied_mahavira
bd2634e81b18        wadmiraal/drupal    "/bin/sh -c 'exec sup"   2 weeks ago         Exited (0) 2 weeks ago                                                            thirsty_hoover
f131bf78ed86        hello-world         "/hello"                 2 weeks ago         Exited (0) 2 weeks ago    

Now for me to have any use of these output I need to be able to get individual container ids etc. I think for that, converting the output to an array of some sort is important. But I have not clue this can be done. Any direction would be highly appreciated.

回答1:

You can entertain yourself using unix tools like grep and awk, something like

docker ps | grep "wadmiraal/drupal" | awk '{print $1}' there you will have ids

It's okay when you use CLI, but if you write teh wrapper, things can go very uncomfortable way, because you will have to split strings, regex parse strings, join strings in arrays, argh.

BUT!

Thanks god, guys from docker team already have teh solution. It's called Docker Remote API , and I think it will fullfill your needs.