How to run commands via NodeJS child process?

随声附和 提交于 2019-11-27 11:48:17
toabi

Sending a newline \n will exectue the command. .end() will exit the shell.

I modified the example to work with bash as I'm on osx.

var terminal = require('child_process').spawn('bash');

terminal.stdout.on('data', function (data) {
    console.log('stdout: ' + data);
});

terminal.on('exit', function (code) {
    console.log('child process exited with code ' + code);
});

setTimeout(function() {
    console.log('Sending stdin to terminal');
    terminal.stdin.write('echo "Hello $USER. Your machine runs since:"\n');
    terminal.stdin.write('uptime\n');
    console.log('Ending terminal session');
    terminal.stdin.end();
}, 1000);

The output will be:

Sending stdin to terminal
Ending terminal session
stdout: Hello root. Your machine runs since:
stdout: 9:47  up 50 mins, 2 users, load averages: 1.75 1.58 1.42
child process exited with code 0

You just have to send line end (\n) with the command:

setTimeout(function() {
    terminal.stdin.write('echo %PATH%\n');
}, 2000);

You can use child_process exec method. here is an example:

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

child = exec('echo %PATH%',
    function (error, stdout, stderr) {
        if(stdout!==''){
            console.log('---------stdout: ---------\n' + stdout);
        }
        if(stderr!==''){
            console.log('---------stderr: ---------\n' + stderr);
        }
        if (error !== null) {
            console.log('---------exec error: ---------\n[' + error+']');
        }
    });

Make sure you stdin.end() at some point or the child process won't exit.

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