linux - Node JS : Executing command lines and getting outputs asynchronously

标签 linux node.js asynchronous command-line output

我怎样才能运行命令行并尽快获得输出以在某处显示它们。

例如,如果在 linux 系统上运行 ping 命令,它永远不会停止,现在是否有可能在命令仍在处理时获得响应? 或者让我们使用 apt-get install 命令,如果我想在安装运行时显示安装进度怎么办?

实际上我正在使用这个函数来执行命令行并获取输出,但是该函数在命令行结束之前不会返回,所以如果我运行 ping 命令它永远不会返回!

var sys     = require('sys'),
    exec    = require('child_process').exec;

function getOutput(command,callback){
    exec(
        command, 
        (
            function(){
                return function(err,data,stderr){
                    callback(data);
                }
            }
        )(callback)
    );
}

最佳答案

尝试使用 spawn 而不是 exec,然后您可以进入流并监听数据和结束事件。

var process = require('child_process');

var cmd = process.spawn(command);

cmd.stdout.on('data', function(output){
    console.log(output.toString()):
});

cmd.on('close', function(){
    console.log('Finished');
});

//Error handling
cmd.stderr.on('data', function(err){
    console.log(err);
});

请在此处查看 spawn 的 Node.js 文档:https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options

关于linux - Node JS : Executing command lines and getting outputs asynchronously,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23516740/

相关文章:

java - 设置运行在linux上的Java程序的nice值

javascript - Node.js 中的 REST 客户端

mysql - 在node.js中使用promise处理MySQL返回值

javascript - ForEach(内部有异步函数)完成后的回调

linux - 在 git bash 中找不到 sudo/apt-get 命令

c++ - 如何正确杀死 fork 之子

python - 将我的 PyGtk 3 应用程序移植到 Win32

javascript - $http.get 调用将错误数据返回到 Angular UI-Grid 控件

javascript - 在整个 Express 应用程序中实现单个数据库池的正确方法

c# - SynchronizationContext,什么时候流什么时候不流?