Node JS: Executing command lines and getting outpu

2019-08-07 10:58发布

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条回答
放荡不羁爱自由
2楼-- · 2019-08-07 11:36

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

查看更多
登录 后发表回答