child_process.spawn
函数是 Node.js 中用于异步创建子进程的 API。它接收几个参数,其中最重要的是要执行的命令(command
)、命令的参数数组(args
),以及一个可选的options
对象。options
对象允许你配置子进程的各种行为。
以下是options
对象中可以设置的一些属性:
cwd
:子进程的当前工作目录。env
:环境变量的键值对。stdio
:子进程的stdio配置。可以是'pipe'
、'ipc'
、'ignore'
、'inherit'
,或者是一个整数,表示文件描述符。detached
:准备将子进程独立于父进程运行。uid
:设置子进程的用户标识。gid
:设置子进程的群组标识。shell
:如果为true
,则在shell中运行命令。windowsHide
:在Windows上隐藏子进程的窗口。windowsVerbatimArguments
:在Windows上,允许命令中的参数包含空格或特殊字符,而不需要引号或转义。
以下是一个child_process.spawn
的代码示例,其中使用了options
对象来设置工作目录和环境变量:
const { spawn } = require('child_process');
// 要执行的命令和参数
const command = 'node';
const args = ['script.js'];
// options对象
const options = {
cwd: '/path/to/working/directory', // 设置子进程的工作目录
env: {
NODE_ENV: 'production', // 设置环境变量
PORT: '3000'
},
stdio: 'inherit' // 继承父进程的stdio配置
};
// 创建子进程
const child = spawn(command, args, options);
// 监听子进程的输出
child.stdout.on('data', (data) => {
console.log(`stdout: ${data}`);
});
child.stderr.on('data', (data) => {
console.error(`stderr: ${data}`);
});
// 监听子进程的关闭事件
child.on('close', (code) => {
console.log(`子进程已关闭,退出码:${code}`);
});
在这个例子中,我们设置了子进程的工作目录为/path/to/working/directory
,并设置了两个环境变量NODE_ENV
和PORT
。我们还配置了stdio
为'inherit'
,这意味着子进程将继承父进程的stdio流,因此它的输出将直接打印到父进程的控制台。最后,我们监听了子进程的stdout
、stderr
和close
事件来处理输出和退出码。