Node JS: Executing command lines and getting outputs asynchronously

筅森魡賤 提交于 2019-12-11 02:43:42

问题


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

回答1:


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.toString()):
});

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

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

See the Node.js documentation for spawn here: https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options



来源:https://stackoverflow.com/questions/23516740/node-js-executing-command-lines-and-getting-outputs-asynchronously

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!