命令行stdout到Node.js中的数组 [英] Command line stdout to array in nodejs

查看:109
本文介绍了命令行stdout到Node.js中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试编写一个node.js应用程序以与docker命令行工具接口。我当前的代码如下:

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);
});

我得到以下示例输出:
safwan @ ubuntu:〜/ node $。 /cmd-docker.js

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    

现在让我可以使用这些输出,我需要能够获取单个容器ID等。我认为为此,将输出转换为so的数组我的排序很重要。但是我不知道这是可以做到的。

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.

推荐答案

您可以使用 grep awk
类似于

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


docker ps | grep wadmiraal / drupal | awk'{print $ 1}'
您将有ID

使用CLI,但是如果您编写包装程序,事情可能会很不舒服,因为您将不得不分割字符串,正则表达式解析字符串,将数组中的字符串连接起来等等。

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.

但是!

感谢上帝,码头工人团队的家伙已经有了解决方案。
叫做
Docker远程API ,我认为将满足您的需求。

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

这篇关于命令行stdout到Node.js中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆