How to execute an external program from within Nod

2019-01-04 07:50发布

Is it possible to execute an external program from within node.js? Is there an equivalent to Python's os.system() or any library that adds this functionality?

4条回答
啃猪蹄的小仙女
2楼-- · 2019-01-04 08:26

The simplest way is:

const exec = require("child_process").exec
exec('yourApp').unref()

unref is necessary to end your process without waiting for "yourApp"

Here are the exec docs

查看更多
一夜七次
3楼-- · 2019-01-04 08:38

exec has memory limitation of buffer size of 512k. In this case it is better to use spawn. With spawn one has access to stdout of executed command at run time

var spawn = require('child_process').spawn;
var prc = spawn('java',  ['-jar', '-Xmx512M', '-Dfile.encoding=utf8', 'script/importlistings.jar']);

//noinspection JSUnresolvedFunction
prc.stdout.setEncoding('utf8');
prc.stdout.on('data', function (data) {
    var str = data.toString()
    var lines = str.split(/(\r?\n)/g);
    console.log(lines.join(""));
});

prc.on('close', function (code) {
    console.log('process exit code ' + code);
});
查看更多
Fickle 薄情
4楼-- · 2019-01-04 08:46

From the Node.js documentation:

Node provides a tri-directional popen(3) facility through the ChildProcess class.

See http://nodejs.org/docs/v0.4.6/api/child_processes.html

查看更多
孤傲高冷的网名
5楼-- · 2019-01-04 08:50
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
    // result
});
查看更多
登录 后发表回答