This article will take you to understand the subprocess in Node.js, and introduce the four methods of creating subprocesses in Node.js. I hope it will be helpful to everyone!
As we all know, Node.js is a single-threaded, asynchronous and non-blocking programming language. So how to make full use of the advantages of multi-core CPUs? This requires the child_process module to create a child process. In Node.js, there are four ways to create a child process:
exec
execFile
##spawn
fork
nodejs tutorial"]
The above four methods will returnChildProcess instance (inherited from
EventEmitter), which has three standard stdio streams:
child.stdin
child.stdout
: Triggered when the child process ends. The parameters are the code error code and the signal interrupt signal.
: Triggered when the child process ends and the stdio stream is closed. The parameters are the same as the exit
event.
: Triggered when the parent process calls child.disconnect()
or the child process calls process.disconnect()
.
: Triggered when the child process cannot be created, cannot be killed, or fails to send a message to the child process.
: Triggered when the child process sends a message through process.send()
.
: Triggered when the child process is successfully created (this event was only added in Node.js v15.1). The
and execFile
methods also provide an additional callback function, which will be triggered when the child process terminates. Next, detailed analysis: exec
const { exec } = require("child_process") exec("find . -type f | wc -l", (err, stdout, stderr) => { if (err) return console.error(`exec error: ${err}`) console.log(`Number of files ${stdout}`) })
exec will create a new sub-process, cache its running results, and call the callback function after the run is completed.
You may have thought that the exec command is relatively dangerous. If you use the string provided by the user as a parameter of the exec function, you will face the risk of command line injection, for example:
find . -type f | wc -l; rm -rf /;
In addition , since exec will cache all output results in memory, when the data is relatively large, spawn will be a better choice.
execFile
const { execFile } = require("child_process") const child = execFile("node", ["--version"], (error, stdout, stderr) => { if (error) throw error console.log(stdout) })
Since there is no creation Shell, the parameters of the program are passed in as an array, so it has high security.
spawn
command: <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">const child = spawn("wc")
process.stdin.pipe(child.stdin)
child.stdout.on("data", data => {
console.log(`child stdout:\n${data}`)
})</pre><div class="contentsignin">Copy after login</div></div>
At this time, the input will be obtained from the command line stdin. When When the user triggers the carriage return
, the command starts executing and the results are output from stdout.
wc [OPTION]... [FILE]...Copy after loginIf you enter the wc command on the terminal and press Enter, the count is from the keyboard. Enter the characters in the terminal, press the Enter key again, and then press
Ctrl Dto output the statistical results.
You can also combine complex commands through pipelines, such as counting the number of files in the current directory. In the Linux command line, it will be written like this:
find . -type f | wc -l
How to write it in Node.js Exactly the same as the command line:
const find = spawn("find", [".", "-type", "f"]) const wc = spawn("wc", ["-l"]) find.stdout.pipe(wc.stdin) wc.stdout.on("data", (data) => { console.log(`Number of files ${data}`) })
spawn has rich custom configurations, for example:
const child = spawn("find . -type f | wc -l", { stdio: "inherit", // 继承父进程的输入输出流 shell: true, // 开启命令行模式 cwd: "/Users/keliq/code", // 指定执行目录 env: { ANSWER: 42 }, // 指定环境变量(默认是 process.env) detached: true, // 作为独立进程存在 })
fork
const { fork } = require("child_process") const forked = fork("./child.js") forked.on("message", msg => { console.log("Message from child", msg); }) forked.send({ hello: "world" })
The child process child.js code:
process.on("message", msg => { console.log("Message from parent:", msg) }) let counter = 0 setInterval(() => { process.send({ counter: counter++ }) }, 1000)
When calling
fork("child.js"), actually Just use node to execute the code in the file, which is equivalent to spawn('node', ['./child.js'])
. A typical application scenario of fork is as follows: If you use Node.js to create an http service, when the route is
, a time-consuming operation is performed. <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:js;toolbar:false;">const http = require("http")
const server = http.createServer()
server.on("request", (req, res) => {
if (req.url === "/compute") {
const sum = longComputation()
return res.end(Sum is ${sum})
} else {
res.end("OK")
}
})
server.listen(3000);</pre><div class="contentsignin">Copy after login</div></div>
You can use the following code to simulate this time-consuming operation:
const longComputation = () => { let sum = 0; for (let i = 0; i < 1e9; i++) { sum += i } return sum }
那么在上线后,只要服务端收到了 compute
请求,由于 Node.js 是单线程的,耗时运算占用了 CPU,用户的其他请求都会阻塞在这里,表现出来的现象就是服务器无响应。
解决这个问题最简单的方法就是把耗时运算放到子进程中去处理,例如创建一个 compute.js
的文件,代码如下:
const longComputation = () => { let sum = 0; for (let i = 0; i < 1e9; i++) { sum += i; } return sum } process.on("message", msg => { const sum = longComputation() process.send(sum) })
再把服务端的代码稍作改造:
const http = require("http") const { fork } = require("child_process") const server = http.createServer() server.on("request", (req, res) => { if (req.url === "/compute") { const compute = fork("compute.js") compute.send("start") compute.on("message", sum => { res.end(Sum is ${sum}) }) } else { res.end("OK") } }) server.listen(3000)
这样的话,主线程就不会阻塞,而是继续处理其他的请求,当耗时运算的结果返回后,再做出响应。其实更简单的处理方式是利用 cluster 模块,限于篇幅原因,后面再展开讲。
掌握了上面四种创建子进程的方法之后,总结了以下三条规律:
更多编程相关知识,请访问:编程视频!!
The above is the detailed content of An in-depth analysis of how to create child processes in Node.js. For more information, please follow other related articles on the PHP Chinese website!