提问者:小点点

使用node.js执行命令行二进制文件


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

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

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

节点中的等价代码是什么?


共1个答案

匿名用户

对于新版本的Node.js(V8.1.4),事件和调用与旧版本相似或相同,但鼓励使用标准的更新语言特性。示例:

对于缓冲的、非流格式的输出(一次获得所有输出),请使用child_process.exec:

const { exec } = require('child_process');
exec('cat *.js bad_file | wc -l', (err, stdout, stderr) => {
  if (err) {
    // node couldn't execute the command
    return;
  }

  // the *entire* stdout and stderr (buffered)
  console.log(`stdout: ${stdout}`);
  console.log(`stderr: ${stderr}`);
});

你也可以和承诺一起使用:

const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function ls() {
  const { stdout, stderr } = await exec('ls');
  console.log('stdout:', stdout);
  console.log('stderr:', stderr);
}
ls();

如果希望以块形式逐渐接收数据(作为流输出),请使用child_process.spawn:

const { spawn } = require('child_process');
const child = spawn('ls', ['-lh', '/usr']);

// use child.stdout.setEncoding('utf8'); if you want text chunks
child.stdout.on('data', (chunk) => {
  // data from standard output is here as buffers
});

// since these are streams, you can pipe them elsewhere
child.stderr.pipe(dest);

child.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});

这两个函数都有一个同步的对应函数。child_process.execsync的示例:

const { execSync } = require('child_process');
// stderr is sent to stderr of parent process
// you can set options.stdio if you want it to go elsewhere
let stdout = execSync('ls');

以及child_process.spawnsync:

const { spawnSync} = require('child_process');
const child = spawnSync('ls', ['-lh', '/usr']);

console.log('error', child.error);
console.log('stdout ', child.stdout);
console.log('stderr ', child.stderr);

注意:下面的代码仍然有效,但主要针对ES5及之前的用户。

使用node.js生成子进程的模块在文档(V5.0.0)中有很好的文档。若要执行命令并将其完整输出作为缓冲区提取,请使用child_process.exec:

var exec = require('child_process').exec;
var cmd = 'prince -v builds/pdf/book.html -o builds/pdf/book.pdf';

exec(cmd, function(error, stdout, stderr) {
  // command output is in stdout
});

如果需要使用带有流的处理进程I/O,例如当需要大量输出时,请使用child_process.spawn:

var spawn = require('child_process').spawn;
var child = spawn('prince', [
  '-v', 'builds/pdf/book.html',
  '-o', 'builds/pdf/book.pdf'
]);

child.stdout.on('data', function(chunk) {
  // output will be here in chunks
});

// or if you want to send output elsewhere
child.stdout.pipe(dest);

如果执行的是文件而不是命令,则可能希望使用child_process.execfile,该参数与spawn几乎相同,但具有第四个回调参数,如exec用于检索输出缓冲区。这看起来可能有点像这样:

var execFile = require('child_process').execFile;
execFile(file, args, options, function(error, stdout, stderr) {
  // command output is in stdout
});

从V0.11.12开始,Node现在支持同步spawnexec。上面描述的所有方法都是异步的,并且有一个同步的对应方。有关它们的文档可以在这里找到。虽然它们对编写脚本很有用,但请注意,与用于异步生成子进程的方法不同,同步方法不会返回childProcess的实例。