nodejs 官网介绍
The node:child_process module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to popen(3). This capability is primarily provided by the child_process.spawn() function:
import { spawn } from '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}`);
});
node:child_process 模块提供了以与 popen(3) 类似但不相同的方式生成子进程的能力。此功能主要由 child_process.spawn() 提供
应用场景
## child/src/index.ts ===== tsc ==> child/dist/index.js
import path from "node:path";
console.log("cwd:",process.cwd())
console.log("PARENT_VAR:",process.env.PARENT_VAR)
console.log("__filename:",path.dirname(__filename))
执行编译后的文件
node dist/index.js
执行结果:
cwd: ${workspace}/child
PARENT_VAR: undefined
__filename: ${workspace}/child/dist
## parent/src/index.ts ===== tsc ==> parent/dist/index.js
import { spawn } from "node:child_process";
let child = spawn(process.execPath, ["../child/dist/index.js"],{ stdio: "inherit" ,detached : true})
child.on("exit",()=>{
console.log("child exit")
})
// stdout
child.stdout?.on("data", (data) => {
console.log(`stdout: ${data}`);
});
// stderr
child.stderr?.on("data", (data) => {
console.error(`stderr: ${data}`);
});
child.unref()
执行编译后的文件:
node dist/index.js
执行结果:
cwd: ${workspace}/parent
PARENT_VAR: undefined
__filename: ${workspace}/child/dist
更新parent/src/index.ts
import { spawn } from "node:child_process";
// 设置环境变量
process.env.PARENT_VAR="pppp"
let child = spawn(process.execPath, ["../child/dist/index.js"],{ stdio: "inherit" ,detached : true})
child.on("exit",()=>{
console.log("child exit")
})
// stdout
child.stdout?.on("data", (data) => {
console.log(`stdout: ${data}`);
});
// stderr
child.stderr?.on("data", (data) => {
console.error(`stderr: ${data}`);
});
child.unref()
执行编译后的文件:
node dist/index.js
执行结果:
cwd: ${workspace}/parent
PARENT_VAR: pppp
__filename: ${workspace}/child/dist
在启动子进程的时候会把当前进程的环境变量传递过去:
child_process.spawn(command[, args][, options])
-
args<string[]> List of string arguments. -
optionscwd| Current working directory of the child process.envEnvironment key-value pairs. Default:process.env.argv0Explicitly set the value ofargv[0]sent to the child process. This will be set tocommandif not specified.stdio| Child's stdio configuration (seeoptions.stdio).detachedPrepare child process to run independently of its parent process. Specific behavior depends on the platform (seeoptions.detached).uidSets the user identity of the process (seesetuid(2)).gidSets the group identity of the process (seesetgid(2)).serializationSpecify the kind of serialization used for sending messages between processes. Possible values are'json'and'advanced'. See Advanced serialization for more details. Default:'json'.shell| Iftrue, runscommandinside of a shell. Uses'/bin/sh'on Unix, andprocess.env.ComSpecon Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shell. Default:false(no shell).windowsVerbatimArgumentsNo quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set totrueautomatically whenshellis specified and is CMD. Default:false.windowsHideHide the subprocess console window that would normally be created on Windows systems. Default:false.signalallows aborting the child process using an AbortSignal.timeoutIn milliseconds the maximum amount of time the process is allowed to run. Default:undefined.killSignal| The signal value to be used when the spawned process will be killed by timeout or abort signal. Default:'SIGTERM'.The
child_process.spawn()method spawns a new process using the givencommand, with command-line arguments inargs. If omitted,argsdefaults to an empty array.If the
shelloption is enabled, do not pass unsanitized user input to this function. Any input containing shell metacharacters may be used to trigger arbitrary command execution.A third argument may be used to specify additional options, with these defaults: