In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "what are the methods of creating child processes in Node.js". The content of the explanation is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "what are the methods of creating child processes in Node.js"?
As we all know, Node.js is a single-threaded, asynchronous non-blocking programming language, so how to take full advantage of multicore CPU? This requires the child_process module to create child processes. In Node.js, there are four ways to create child processes:
Exec
ExecFile
Spawn
Fork
Each of the above four methods returns a ChildProcess instance (inherited from EventEmitter), which has three standard stdio streams:
Child.stdin
Child.stdout
Child.stderr
The events that can register to listen during the life cycle of a child process are:
Exit: triggered when the child process ends, and the parameters are code error code and signal interrupt signal.
Close: triggered when the child process ends and the stdio stream is closed, with the same parameters as the exit event.
Disconnect: triggered when the parent process calls child.disconnect () or the child process calls process.disconnect ().
Error: triggered when a child process cannot be created, cannot be killed, or fails to send a message to the child process.
Message: triggered when a child process sends a message through process.send ().
Spawn: triggered when the child process is created successfully (this event is added only in Node.js v15.1 version).
The exec and execFile methods also provide an additional callback function that is triggered when the child process terminates. The following is a detailed analysis:
Exec
The exec method is used to execute the bash command, whose argument is a command string. For example, to count the number of files in the current directory, the exec function is written as follows:
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 creates a new child process, then caches its running results, and calls the callback function when the run is over.
As you may have thought, the exec command is dangerous. If you take the user-supplied string as an argument to the exec function, you will face the risk of command line injection, for example:
Find. -type f | wc-1; rm-rf /
In addition, because exec caches all the output in memory, spawn is a better choice when the data is large.
ExecFile
ExecFile differs from exec in that it does not create a shell, but executes commands directly, so it is a little more efficient, such as:
Const {execFile} = require ("child_process") const child = execFile ("node", ["- version"], (error, stdout, stderr) = > {if (error) throw error console.log (stdout)})
Because the shell is not created, the parameters of the program are passed in as an array, so it has high security.
Spawn
The spawn function is similar to execFile. Shell is not enabled by default, but the difference is that execFile caches the output of the command line and then passes the result to the callback function, while spawn outputs as a stream. With a stream, you can easily interface input and output, such as a typical wc command:
Const child = spawn ("wc") process.stdin.pipe (child.stdin) child.stdout.on ("data", data = > {console.log (`child stdout:\ n$ {data} `)})
At this point, the input is taken from the command line stdin, and when the user triggers enter + ctrl D, the command is executed and the result is output from stdout.
Wc is an acronym for Word Count and is used to count words. The syntax is:
Wc [OPTION]... [FILE]...
If you enter the wc command on the terminal and enter, you will count the characters in the terminal from the keyboard, press enter again, and then press Ctrl + D to output the statistical results.
You can also combine complex commands through pipes, such as counting the number of files in the current directory, which is written on the Linux command line:
Find. -type f | wc-l
It is written exactly the same way as the command line in Node.js:
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 a wealth of custom configurations, such as:
Const child = spawn ("find.-type f | wc-l", {stdio: "inherit", / / inherit the input and output stream of the parent process shell: true, / / open the command line mode cwd: "/ Users/keliq/code", / / specify the execution directory env: {ANSWER: 42}, / / specify the environment variable (default is process.env) detached: true, / / exist as a stand-alone process}) fork
The fork function is a variant of the spawn function. A communication channel is automatically created between the child process created with fork and the parent process, and the send method is mounted on the global object process of the child process. For example, the parent process parent.js code:
Const {fork} = require ("child_process") const forked = fork (". / child.js") forked.on ("message", msg = > {console.log ("Message from child", msg);}) forked.send ({hello: "world"})
Child process child.js code:
Process.on ("message", msg = > {console.log ("Message from parent:", msg)}) let counter = 0setInterval (() = > {process.send ({counter: counter++})}, 1000)
When you call fork ("child.js"), you are actually using node to execute the code in that file, which is equivalent to spawn ('node', ['. / child.js']).
A typical application scenario for fork is as follows: if you create a http service with Node.js now, perform a time-consuming operation when the route is compute.
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)
You can simulate this time-consuming operation with the following code:
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)})
Then modify the server code a little bit:
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)
In this way, the main thread will not block, but will continue to process other requests and respond when the results of the time-consuming operation are returned. In fact, a simpler way to deal with it is to use the cluster module, which is limited to space and will be discussed later.
Summary
After mastering the above four methods of creating child processes, the following three rules are summarized:
The fork is used to create the node child process, because it has its own channel to facilitate communication.
Create non-node child processes using execFile or spawn. If the output uses less execFile, the result will be cached and passed to the callback for convenient processing; if the output uses more spawn, the streaming method will not take up a lot of memory.
Execute complex, fixed terminal commands with exec, which is more convenient to write. It is important to remember, however, that exec creates shell, is not as efficient as execFile and spawn, and there is a risk of command line injection.
Thank you for your reading, the above is the content of "what are the methods of creating child processes in Node.js". After the study of this article, I believe you have a deeper understanding of the method of creating child processes in Node.js, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.