使用 Node.js 执行命令行二进制文件 [英] Execute a command line binary with Node.js

查看:46
本文介绍了使用 Node.js 执行命令行二进制文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am in the process of porting a CLI library from Ruby over to Node.js. In my code I execute several third party binaries when necessary. I am not sure how best to accomplish this in Node.

这是我在 Ruby 中调用 PrinceXML 将文件转换为 PDF 的示例:

Here's an example in Ruby where I call PrinceXML to convert a file to a PDF:

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

Node 中的等效代码是什么?

What is the equivalent code in Node?

推荐答案

对于较新版本的 Node.js (v8.1.4),事件和调用与旧版本相似或相同,但鼓励使用标准较新的语言功能.示例:

For even newer version of Node.js (v8.1.4), the events and calls are similar or identical to older versions, but it's encouraged to use the standard newer language features. Examples:

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

For buffered, non-stream formatted output (you get it all at once), use 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}`);
});

您也可以将其与 Promise 一起使用:

You can also use it with Promises:

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:

If you wish to receive the data gradually in chunks (output as a stream), use 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 的示例:

Both of these functions have a synchronous counterpart. An example for 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 及之前版本的用户.


Note: The following code is still functional, but is primarily targeted at users of ES5 and before.

使用 Node.js 生成子进程的模块在 文档中有详细记录 (v5.0.0).要执行命令并将其完整输出作为缓冲区获取,请使用 child_process.exec:

The module for spawning child processes with Node.js is well documented in the documentation (v5.0.0). To execute a command and fetch its complete output as a buffer, use 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:

If you need to use handle process I/O with streams, such as when you are expecting large amounts of output, use 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用于检索输出缓冲器.这可能看起来有点像这样:

If you are executing a file rather than a command, you might want to use child_process.execFile, which parameters which are almost identical to spawn, but has a fourth callback parameter like exec for retrieving output buffers. That might look a bit like this:

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.


As of v0.11.12, Node now supports synchronous spawn and exec. All of the methods described above are asynchronous, and have a synchronous counterpart. Documentation for them can be found here. While they are useful for scripting, do note that unlike the methods used to spawn child processes asynchronously, the synchronous methods do not return an instance of ChildProcess.

这篇关于使用 Node.js 执行命令行二进制文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆