如何使用Node.js执行CLI指令?

本文主要讲述如何在nodejs脚本中执行命令行指令。

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

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

1
2
3
4
5
6
7
8
9
10
11
12
13

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一起使用:

1
2
3
4
5
6
7
8
9
10
11

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

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的示例:

1
2
3
4
5
6
7
8

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及之前版本的javascript语法。

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

1
2
3
4
5
6
7
8

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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

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,用于检索输出缓冲区。

1
2
3
4
5
6

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

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

参考文档

Execute a command line binary with Node.js

作者

鹏叔

发布于

2025-04-24

更新于

2025-04-25

许可协议

评论