The code copy 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 above example provides a Fibonacci sequence calculation service. Since this calculation is quite time-consuming and is a single thread, only one can be processed when there are multiple requests at the same time. This problem can be solved through child_process.fork().
Here is an example on the official website. This example can be used to understand the function of fork() well.
The code copy 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' });
The result of executing the above code snippet:
The code copy is as follows:
PARENT got message: { foo: 'bar' }
CHILD got message: { hello: 'world' }
The content of sub.js is as follows:
The code copy is as follows:
process.on('message', function(m) {
console.log('CHILD got message:', m);
});
process.send({ foo: 'bar' });
The process object has a send() method in the child process, and it will publish the message object every time it receives a message
What is a little dizzy is that the message sent by child.send() is received by the process.on() method, and the message sent by the process.send() method is received by the child.on() method.
Referring to this example, we can improve the first service that provides Fibonacci data, so that each request has a separate new process to handle it.
The code copy 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 child process individually
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 copy 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 starting the service, visit http://localhost:8080/9 to calculate the value of the Fibonacci sequence of 9.
The above is all about this article, I hope you like it.