Node.js执行shell命令

如何在Node.js中执行shell命令
创作声明:包含 AI 辅助创作

Node.js可以通过child_process模块执行shell命令和脚本。主要有以下几种方法:

使用exec()

exec()方法可以执行shell命令,并缓冲输出结果。适用于短时间的命令,获取完整的输出。

1
2
3
4
5
6
7
8
9
10
const { exec } = require('child_process'); 

exec('ls -l', (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.log(`stderr: ${stderr}`);
});

使用execFile()

execFile()直接执行命令,可以获取流式输出。适用于需要实时交互的命令。

1
2
3
4
5
6
7
8
9
10
11
12
13
const { execFile } = require('child_process');

const child = execFile('node', ['--version'], (error, stdout, stderr) => {
if (error) {
throw error;
}

// 实时打印输出
stdout.on('data', (data) => {
console.log(data);
});

});

使用spawn()

spawn()会新启一个shell执行命令,可以方便处理大量的数据。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
const { spawn } = require('child_process');

// 实例化ls命令
const ls = spawn('ls', ['-lh', '/usr']);

// 处理标准输出
ls.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});

// 处理标准错误输出
ls.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});

// 处理退出
ls.on('close', (code) => {
console.log(`子进程退出码:${code}`);
});

参数选项

这些方法都支持额外的参数来配置执行的命令,例如指定 cwd、env、stdin 等。

使用建议
短时间命令获取完整输出,使用 exec()
需要实时交互,使用 execFile() 或 spawn()
长时间运行进程,适合使用 spawn()
选择合适的方法,可以在Node.js中高效执行shell命令。


Node.js执行shell命令
http://example.com/20231018-Node.js执行shell命令/
作者
csorz
发布于
2023年10月18日
许可协议