如何从内Node.js的执行外部程序?

问题描述 投票:125回答:4

是否有可能从node.js的内执行外部程序?是否有一个相当于Python的os.system()或添加此功能的任何图书馆吗?

node.js command exec
4个回答
130
投票
var exec = require('child_process').exec;
exec('pwd', function callback(error, stdout, stderr){
    // result
});

70
投票

EXEC具有512K的缓冲区大小的存储器限制。在这种情况下,最好使用产卵。随着产卵一个具有在运行时获得执行的命令的标准输出

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

15
投票

最简单的方法是:

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

UNREF要结束你的程序,而无需等待“yourApp”

下面是EXEC docs


4
投票

从Node.js的文档:

节点提供一个三向POPEN(3)设备通过子进程类。

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

© www.soinside.com 2019 - 2024. All rights reserved.