我正在将一个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

其他回答

节点JS 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() }` );

来自Node.js v15.8.0文档

Node.js v14.15.4文档和Node.js v12.20.1文档也是如此

如果您不介意依赖关系,并且希望使用promise,那么子进程promise可以:

安装

npm install child-process-promise --save

exec用法

var exec = require('child-process-promise').exec;
 
exec('echo hello')
    .then(function (result) {
        var stdout = result.stdout;
        var stderr = result.stderr;
        console.log('stdout: ', stdout);
        console.log('stderr: ', stderr);
    })
    .catch(function (err) {
        console.error('ERROR: ', err);
    });

派生用法

var spawn = require('child-process-promise').spawn;
 
var promise = spawn('echo', ['hello']);
 
var childProcess = promise.childProcess;
 
console.log('[spawn] childProcess.pid: ', childProcess.pid);
childProcess.stdout.on('data', function (data) {
    console.log('[spawn] stdout: ', data.toString());
});
childProcess.stderr.on('data', function (data) {
    console.log('[spawn] stderr: ', data.toString());
});
 
promise.then(function () {
        console.log('[spawn] done!');
    })
    .catch(function (err) {
        console.error('[spawn] ERROR: ', err);
    });

ECMAScript模块导入。。。from语法

import {exec} from 'child-process-promise';
let result = await exec('echo hi');
console.log(result.stdout);

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

var shell = require('shelljs');

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

使用安装

npm install shelljs

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

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

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

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

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

对于更新版本的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');

以及child_process.s当兵同步:

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.00)中有详细说明。要执行命令并获取其完整输出作为缓冲区,请使用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
});

如果您需要对流使用handle process 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,这些参数与派生几乎相同,但有第四个回调参数(如exec)用于检索输出缓冲区。看起来可能有点像这样:

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

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