我正在将 CLI 库从 Ruby 移植到 Node.js。在我的代码中,如有必要,我将执行几个第三方二进制文件。我不确定如何最好地在 Node 中完成此操作。
这是 Ruby 中的一个示例,其中我调用 PrinceXML 将文件转换为 PDF:
cmd = system("prince -v builds/pdf/book.html -o builds/pdf/book.pdf")
Node 中的等效代码是什么?
对于更高版本的 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}`);
});
您也可以将其与 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
:
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');
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 及更高版本的用户。
在文档(v5.0.0)中很好地记录了使用 Node.js 生成子进程的模块。要执行命令并获取其完整的输出作为缓冲区,请使用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
});
child_process.spawn
使用句柄进程 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 现在支持同步spawn
和exec
。上述所有方法都是异步的,并且具有同步的对应方法。 可以在此处找到有关它们的文档。尽管它们对于脚本编写很有用,但请注意,与用于异步生成子进程的方法不同,同步方法不会返回ChildProcess
的实例。
v15.8.0
,LTS v14.15.4
和v12.20.1
2021 年 2 月异步方法(Unix):
'use strict';
const { spawn } = require( 'child_process' );
const ls = spawn( 'ls', [ '-lh', '/usr' ] );
ls.stdout.on( 'data', ( data ) => {
console.log( `stdout: ${ data }` );
} );
ls.stderr.on( 'data', ( data ) => {
console.log( `stderr: ${ data }` );
} );
ls.on( 'close', ( code ) => {
console.log( `child process exited with code ${ code }` );
} );
异步方法(Windows):
'use strict';
const { spawn } = require( 'child_process' );
// NOTE: Windows Users, this command appears to be differ for a few users.
// You can think of this as using Node to execute things in your Command Prompt.
// If `cmd` works there, it should work here.
// If you have an issue, try `dir`:
// const dir = spawn( 'dir', [ '.' ] );
const dir = spawn( 'cmd', [ '/c', 'dir' ] );
dir.stdout.on( 'data', ( data ) => console.log( `stdout: ${ data }` ) );
dir.stderr.on( 'data', ( data ) => console.log( `stderr: ${ data }` ) );
dir.on( 'close', ( code ) => console.log( `child process exited with code ${code}` ) );
同步:
'use strict';
const { spawnSync } = require( 'child_process' );
const ls = spawnSync( 'ls', [ '-lh', '/usr' ] );
console.log( `stderr: ${ ls.stderr.toString() }` );
console.log( `stdout: ${ ls.stdout.toString() }` );
您正在寻找child_process.exec
这是示例:
const exec = require('child_process').exec;
const child = exec('cat *.js bad_file | wc -l',
(error, stdout, stderr) => {
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
if (error !== null) {
console.log(`exec error: ${error}`);
}
});