深入了解nodejs spawn执行的流程

149 阅读1分钟

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])
  • command  The command to run.

  • args <string[]> List of string arguments.

  • options 

    • cwd  |  Current working directory of the child process.
    • env  Environment key-value pairs. Default:  process.env.
    • argv0  Explicitly set the value of argv[0] sent to the child process. This will be set to command if not specified.
    • stdio  |  Child's stdio configuration (see options.stdio).
    • detached  Prepare child process to run independently of its parent process. Specific behavior depends on the platform (see options.detached).
    • uid  Sets the user identity of the process (see setuid(2)).
    • gid  Sets the group identity of the process (see setgid(2)).
    • serialization  Specify 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  |  If true, runs command inside of a shell. Uses '/bin/sh' on Unix, and process.env.ComSpec on Windows. A different shell can be specified as a string. See Shell requirements and Default Windows shellDefault:  false (no shell).
    • windowsVerbatimArguments  No quoting or escaping of arguments is done on Windows. Ignored on Unix. This is set to true automatically when shell is specified and is CMD. Default:  false.
    • windowsHide  Hide the subprocess console window that would normally be created on Windows systems. Default:  false.
    • signal  allows aborting the child process using an AbortSignal.
    • timeout  In 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'.
    • Returns: 

    • The child_process.spawn() method spawns a new process using the given command, with command-line arguments in args. If omitted, args defaults to an empty array.

      If the shell option 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: