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

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

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

Node中的等效代码是什么?


当前回答

您正在查找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}`);
        }
});

其他回答

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

看看这里。

按如下方式导入:

const system = require('system-commands')

运行以下命令:

system('ls').then(output => {
    console.log(output)
}).catch(error => {
    console.error(error)
})
const exec = require("child_process").exec
exec("ls", (error, stdout, stderr) => {
 //do whatever here
})

节点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文档也是如此

您正在查找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}`);
        }
});

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

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

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

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