node:child_process模块提供了以类似于popen(3)的方式生成子进程的能力,但不完全相同。此功能主要由child_process.spawn()函数提供:
js
const { spawn } = require('node:child_process');
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(`child process exited with code ${code}`);
});const { spawn } = require('node:child_process');
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(`child process exited with code ${code}`);
});stdio
stdio选项用于配置在父进程和子进程之间建立的管道。默认情况下,子进程的 stdin、stdout 和 stderr 会重定向到ChildProcess对象上相应的subprocess.stdin 、 subprocess.stdout和subprocess.stderr流。
为了简便期间,stdio: 'inherit' 等同于 stdio: ['inherit', 'inherit', 'inherit']。
'pipe': equivalent to['pipe', 'pipe', 'pipe'](the default)'overlapped': equivalent to['overlapped', 'overlapped', 'overlapped']'ignore': equivalent to['ignore', 'ignore', 'ignore']'inherit': equivalent to['inherit', 'inherit', 'inherit']or[0, 1, 2]
shell
默认值: false (无 shell)。
- 如果为
true,则在 shell 内运行command。在 Unix 上使用'/bin/sh',在 Windows 上使用p。可以将不同的 shell 指定为字符串。请参阅Shell 要求和默认 Windows shellrocess.env.ComSpec
p是一个环境变量,它存储了当前计算机的命令行解释器的路径。在 Windows 系统中,通常这个环境变量的值是rocess.env.ComSpec C:\Windows\System32\cmd.exe
例如执行,如下代码,在windows上执行命令时会报错:
js
spawn('npm', {
stdio: 'inherit'
});spawn('npm', {
stdio: 'inherit'
});因为在 Windows 上,当我们执行 npm 时,我们实际执行的是
npm.cmd批处理,而在 Windows 上,.cmd,.bat批处理是无法脱离cmd.exe这一解释器而单独运行的。
可以修改为
js
spawn('npm', {
stdio: 'inherit',
shell: true
});spawn('npm', {
stdio: 'inherit',
shell: true
});或者显示调用cmd:
js
spawn('cmd', ['/c', 'npm'], {
stdio: 'inherit'
});spawn('cmd', ['/c', 'npm'], {
stdio: 'inherit'
});