- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Corepack
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:module
API - Modules: Packages
- Net
- OS
- Path
- Performance hooks
- Permissions
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
Node.js v18.12.1 documentation
- Node.js v18.12.1
-
► Table of contents
- Child process
- Asynchronous process creation
- Synchronous process creation
- Class:
ChildProcess
- Event:
'close'
- Event:
'disconnect'
- Event:
'error'
- Event:
'exit'
- Event:
'message'
- Event:
'spawn'
subprocess.channel
subprocess.connected
subprocess.disconnect()
subprocess.exitCode
subprocess.kill([signal])
subprocess.killed
subprocess.pid
subprocess.ref()
subprocess.send(message[, sendHandle[, options]][, callback])
subprocess.signalCode
subprocess.spawnargs
subprocess.spawnfile
subprocess.stderr
subprocess.stdin
subprocess.stdio
subprocess.stdout
subprocess.unref()
- Event:
maxBuffer
and Unicode- Shell requirements
- Default Windows shell
- Advanced serialization
- Child process
-
► Index
- Assertion testing
- Asynchronous context tracking
- Async hooks
- Buffer
- C++ addons
- C/C++ addons with Node-API
- C++ embedder API
- Child processes
- Cluster
- Command-line options
- Console
- Corepack
- Crypto
- Debugger
- Deprecated APIs
- Diagnostics Channel
- DNS
- Domain
- Errors
- Events
- File system
- Globals
- HTTP
- HTTP/2
- HTTPS
- Inspector
- Internationalization
- Modules: CommonJS modules
- Modules: ECMAScript modules
- Modules:
node:module
API - Modules: Packages
- Net
- OS
- Path
- Performance hooks
- Permissions
- Process
- Punycode
- Query strings
- Readline
- REPL
- Report
- Stream
- String decoder
- Test runner
- Timers
- TLS/SSL
- Trace events
- TTY
- UDP/datagram
- URL
- Utilities
- V8
- VM
- WASI
- Web Crypto API
- Web Streams API
- Worker threads
- Zlib
- ► Other versions
- ► Options
Table of contents
- Child process
- Asynchronous process creation
- Synchronous process creation
- Class:
ChildProcess
- Event:
'close'
- Event:
'disconnect'
- Event:
'error'
- Event:
'exit'
- Event:
'message'
- Event:
'spawn'
subprocess.channel
subprocess.connected
subprocess.disconnect()
subprocess.exitCode
subprocess.kill([signal])
subprocess.killed
subprocess.pid
subprocess.ref()
subprocess.send(message[, sendHandle[, options]][, callback])
subprocess.signalCode
subprocess.spawnargs
subprocess.spawnfile
subprocess.stderr
subprocess.stdin
subprocess.stdio
subprocess.stdout
subprocess.unref()
- Event:
maxBuffer
and Unicode- Shell requirements
- Default Windows shell
- Advanced serialization
Child process子进程#
Source Code: lib/child_process.js
The node:child_process
module provides the ability to spawn subprocesses in a manner that is similar, but not identical, to popen(3)
. node:child_process
模块提供了以与popen(3)
类似但不相同的方式生成子流程的能力。This capability is primarily provided by the 此功能主要由child_process.spawn()
function:child_process.spawn()
函数提供:
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}`);
});
By default, pipes for 默认情况下,在父Node.js进程和派生的子进程之间建立stdin
, stdout
, and stderr
are established between the parent Node.js process and the spawned subprocess. stdin
、stdout
和stderr
的管道。These pipes have limited (and platform-specific) capacity. 这些管道的容量有限(和平台特定)。If the subprocess writes to stdout in excess of that limit without the output being captured, the subprocess blocks waiting for the pipe buffer to accept more data. 如果子进程在未捕获输出的情况下向stdout写入超过该限制,则子进程将阻塞,等待管道缓冲区接受更多数据。This is identical to the behavior of pipes in the shell. 这与壳中管道的行为相同。Use the 如果不使用输出,请使用{ stdio: 'ignore' }
option if the output will not be consumed.{ stdio: 'ignore' }
选项。
The command lookup is performed using the 如果options.env.PATH
environment variable if env
is in the options
object. env
在options
对象中,则使用options.env.PATH
环境变量执行命令查找。Otherwise, 否则,将使用process.env.PATH
is used. process.env.PATH
。If 如果options.env
is set without PATH
, lookup on Unix is performed on a default search path search of /usr/bin:/bin
(see your operating system's manual for execvpe/execvp), on Windows the current processes environment variable PATH
is used.options.env
设置为不带PATH
,则Unix上的查找将在默认搜索路径搜索/usr/bin:/bin
(请参阅操作系统的execvpe/execvp手册)上执行,在Windows上使用当前进程环境变量PATH
。
On Windows, environment variables are case-insensitive. 在Windows上,环境变量不区分大小写。Node.js lexicographically sorts the Node.js对env
keys and uses the first one that case-insensitively matches. env
键进行字典排序,并使用不区分大小写匹配的第一个键。Only first (in lexicographic order) entry will be passed to the subprocess. 只有第一个(按词典顺序)条目将传递给子流程。This might lead to issues on Windows when passing objects to the 这可能会导致Windows在向env
option that have multiple variants of the same key, such as PATH
and Path
.env
选项传递具有相同密钥的多个变体(如PATH
和Path
)的对象时出现问题。
The child_process.spawn()
method spawns the child process asynchronously, without blocking the Node.js event loop. child_process.spawn()
方法异步生成子进程,而不阻塞Node.js事件循环。The child_process.spawnSync()
function provides equivalent functionality in a synchronous manner that blocks the event loop until the spawned process either exits or is terminated.child_process.spawnSync()
函数以同步的方式提供了等效的功能,在派生进程退出或终止之前阻止事件循环。
For convenience, the 为了方便起见,node:child_process
module provides a handful of synchronous and asynchronous alternatives to child_process.spawn()
and child_process.spawnSync()
. node:child_process
模块提供了child_process.spawn()
和child_process.spawnSync()
的一些同步和异步替代方案。Each of these alternatives are implemented on top of 这些替代方案都是在child_process.spawn()
or child_process.spawnSync()
.child_process.spawn()
或child_process.spawnSync()
之上实现的。
child_process.exec()
: spawns a shell and runs a command within that shell, passing the:生成一个shell并在该shell中运行一个命令,完成后将stdout
andstderr
to a callback function when complete.stdout
和stderr
传递给回调函数。child_process.execFile()
: similar to:类似于child_process.exec()
except that it spawns the command directly without first spawning a shell by default.child_process.exec()
,不同的是默认情况下它直接生成命令而不首先生成shell。child_process.fork()
: spawns a new Node.js process and invokes a specified module with an IPC communication channel established that allows sending messages between parent and child.:生成一个新的Node.js进程并调用一个指定的模块,该模块具有一个IPC通信信道,该信道允许在父级和子级之间发送消息。child_process.execSync()
: a synchronous version of:child_process.exec()
that will block the Node.js event loop.child_process.exec()
的同步版本,它将阻止Node.js事件循环。child_process.execFileSync()
: a synchronous version of:child_process.execFile()
that will block the Node.js event loop.child_process.execFile()
的同步版本,它将阻止Node.js事件循环。
For certain use cases, such as automating shell scripts, the synchronous counterparts may be more convenient. 对于某些用例,例如自动化shell脚本,同步对应可能更方便。In many cases, however, the synchronous methods can have significant impact on performance due to stalling the event loop while spawned processes complete.然而,在许多情况下,由于在派生进程完成时暂停事件循环,同步方法可能会对性能产生重大影响。