节点JS:执行命令行和获取输出异步 [英] Node JS: Executing command lines and getting outputs asynchronously

查看:586
本文介绍了节点JS:执行命令行和获取输出异步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何运行一个命令行,一旦获得可输出到某处显示它们。

例如,如果在Linux系统上运行ping命令,它永远不会停止,现在是有可能得到的答复,而命令仍在处理?
还是让我们的apt-get安装命令,如果我想显示安装进度,因为它是运行?

其实我使用这个功能来执行命令行,并得到输出,但功能不会返回到命令行结束,所以如果我运行一个ping命令它永远不会返回!

  VAR SYS =要求('SYS'),
    EXEC =要求('child_process')EXEC。功能getOutput(指挥,回调){
    EXEC(
        命令,
        (
            功能(){
                返回功能(ERR,数据,标准错误){
                    回调(数据);
                }
            }
        )(回电话)
    );
}


解决方案

尝试使用产卵,而不是EXEC,那么你就可以接入流,并听取了数据和结束事件。

  VAR过程=要求('child_process');VAR CMD = process.spawn(命令);cmd.stdout.on(数据,功能(输出){
    的console.log(输出):
});cmd.on(关闭,函数(){
    的console.log('完成');
});//错误处理
cmd.stderr.on(数据,功能(错误){
    的console.log(ERR);
});

How can I run a command line and get the outputs as soon as available to show them somewhere.

For example if a run ping command on a linux system, it will never stop, now is it possible to get the responses while the command is still processing ? Or let's take apt-get install command, what if i want to show the progress of the installation as it is running ?

Actually i'm using this function to execute command line and get outputs, but the function will not return until the command line ends, so if i run a ping command it will never return!

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

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

解决方案

Try using spawn instead of exec, then you can tap into the stream and listen to the data and end events.

var process = require('child_process');

var cmd = process.spawn(command);

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

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

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

这篇关于节点JS:执行命令行和获取输出异步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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