如何从 Node.js 中执行外部程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5775088/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to execute an external program from within Node.js?
提问by Michael Bylstra
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?
是否可以从 node.js 中执行外部程序?是否有等效于 Pythonos.system()或任何添加此功能的库?
回答by Mark Kahn
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
// result
});
回答by MKK
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
exec 有 512k 缓冲区大小的内存限制。在这种情况下,最好使用 spawn。使用 spawn 可以在运行时访问已执行命令的标准输出
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);
});
回答by zag2art
回答by Michelle Tilley
From the Node.js documentation:
从 Node.js 文档:
Node provides a tri-directional popen(3) facility through the ChildProcess class.
Node 通过 ChildProcess 类提供了一个三向的 popen(3) 工具。

