Nodejs implements multiple processes

Source: Internet
Author: User

Generally, a single node is started to run in a single process. How can I run multiple processes like Nginx?
To implement multi-process, you need to pay attention to the two built-in node modules:
Child_process: Sub-Process Module
Net: Network Module
The Subprocess module of nodejs provides a send function, which is very useful and can pass the data of the main process to the subprocess.
That is to say, we can communicate with sub-processes through the send function.
Then we can implement a tcp server through the net module, and then pass handle to the sub-process. Then, the sub-process can monitor the same port to implement multiple processes.

Main process:
[Javascript]
Var child_process = require ('child _ Process ');
Var net = require ("net ");
Var tcp = net. createServer ();
Tcp. listen (listen, function (){
Console. log ('fork process start ');
Console. log ('Listen: '+ listen );
For (var I = 0; I <processLen; I ++ ){
Start_process (child_process, tcp, indexFile); // start the process
}
Console. log ('fork process end \ r \ n ');
Tcp. close ();
});
/*
* Start the process and monitor the process. If the process exits, the function is automatically called to restart it.
*/
Var start_process = function (child_process, tcp, indexFile ){
Var cp = child_process.fork (indexFile); // generate sub-process, indexFile process file address
Cp. send ('yes', tcp. _ handle); // send data to the child process
Console. log ('pid: '+ cp. pid );
Cp. on ('exit ', function (){
Start_process (child_process, tcp, indexFile );
})
}

Sub-process:
[Javascript]
// The sub-process receives the main process handle
Process. on ("message", function (m, handle) {// listen to the data transmitted by the main process through the process message
Http. createServer (_ this. on). listen (handle); // run the HTTP server
});

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.