This article mainly introduces the implementation of multi-process by child_process in Node. js. For more information, see
The code is as follows:
Var http = require ('http ');
Function fib (n ){
If (n <2 ){
Return 1;
} Else {
Return fib (n-2) + fib (n-1 );
}
}
Var server = http. createServer (function (req, res ){
Var num = parseInt (req. url. substring (1), 10 );
Res. writeHead (200 );
Res. end (fib (num) + "\ n ");
});
Server. listen (8000 );
The preceding example provides a Fibonacci series computing service. because the computing is time-consuming and is a single thread, only one request can be processed at the same time, through child_process.fork () you can solve this problem.
Here is an example on the official website. The fork () function can be well understood through this example.
The code is as follows:
Var cp = require ('child _ process ');
Var n = cp. fork (_ dirname + '/sub. js ');
N. on ('message', function (m ){
Console. log ('parent got message: ', m );
});
N. send ({hello: 'World '});
Run the following code snippet:
The code is as follows:
PARENT got message: {foo: 'bar '}
CHILD got message: {hello: 'World '}
The sub. js content is as follows:
The code is as follows:
Process. on ('message', function (m ){
Console. log ('child got message: ', m );
});
Process. send ({foo: 'bar '});
In a sub-process, the process object has the send () method. at the same time, it publishes a message object every time it receives a message.
A little dizzy: child. the message sent by send () is sent by process. received by the on () method, process. the message sent by the send () method is sent by the child. received by the on () method
With reference to this example, we can improve the first service that provides Fibonacci data so that each request has a new process to process.
The code is as follows:
Var http = require ('http ');
Var cp = require ('child _ process ');
Var server = http. createServer (function (req, res ){
Var child = cp. fork (_ dirname + '/fibonacci-calc.js'); // Each request generates a new sub-process
Child. on ('message', function (m ){
Res. end (m. result + '\ n ');
});
Var input = parseInt (req. url. substring (1 ));
Child. send ({input: input });
});
Server. listen (8000 );
Fibonacci-calc.js
The code is as follows:
Function fib (n ){
If (n <2 ){
Return 1;
} Else {
Return fib (n-2) + fib (n-1 );
}
}
Process. on ('message', function (m ){
Process. send ({result: fib (m. input )});
});
After the service is started, you can access http: // localhost: 8080/9 to calculate the value of the 9 Fibonacci series.
The above is all the content of this article. I hope you will like it.