我正在将一个CLI库从Ruby移植到Node.js。在我的代码中,必要时我会执行几个第三方二进制文件。我不确定如何在Node中实现这一点。

下面是Ruby中的一个示例,我调用PrinceXML将文件转换为PDF:

cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")

Node中的等效代码是什么?


当前回答

现在,可以按如下方式使用shelljs(从节点v4):

var shell = require('shelljs');

shell.echo('hello world');
shell.exec('node --version');

使用安装

npm install shelljs

看见https://github.com/shelljs/shelljs

其他回答

使用这个轻量级npm包:系统命令

看看这里。

按如下方式导入:

const system = require('system-commands')

运行以下命令:

system('ls').then(output => {
    console.log(output)
}).catch(error => {
    console.error(error)
})

如果你想要一个与顶级答案非常相似但同时也是同步的答案,那么这将起作用。

var execSync = require('child_process').execSync;
var cmd = "echo 'hello world'";

var options = {
  encoding: 'utf8'
};

console.log(execSync(cmd, options));

由于版本4,最接近的替代方法是child_process.execSync方法:

const {execSync} = require('child_process');

let output = execSync('prince -v builds/pdf/book.html -o builds/pdf/book.pdf');

⚠️ 请注意,execSync调用会阻塞事件循环。

现在,可以按如下方式使用shelljs(从节点v4):

var shell = require('shelljs');

shell.echo('hello world');
shell.exec('node --version');

使用安装

npm install shelljs

看见https://github.com/shelljs/shelljs

const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
 //do whatever here
})