Nodejs simple getting started tutorial (3): Process _ node. js

Source: Internet
Author: User
This article mainly introduces Nodejs simple getting started tutorial (3): process. This article describes the communication between Node processes and cluster modules, for more information, see Node. Although there are multiple threads, JavaScript running on v8 is single-threaded. The child_process module of Node is used to create sub-processes. We can use the sub-processes to make full use of the CPU. Example:

The Code is as follows:


Var fork = require ('child _ Process'). fork;
// Obtain the number of CPUs of the Current Machine
Var cpus = require ('OS'). cpus ();
For (var I = 0; I <cpus. length; I ++ ){
// Generate a new process
Fork ('./worker. js ');
}

Here we will learn how to create several processes, including fork:

1. spawn (command, [args], [options]), start a new process to execute the command. args is the command line parameter.
2. exec (command, [options], callback): Start a new process to execute the command. callback is used to obtain standard input, standard output, and error information at the end of the process.
3. execFile (file, [args], [options], [callback]), start a new process to execute the executable file, callback is used to obtain standard input, standard output, and error information at the end of a process.
4. fork (modulePath, [args], [options]), start a new process to execute a JavaScript file module. At this time, a Node sub-process is created.

Node inter-process communication

Parent Process

The Code is as follows:


// Parent. js
Var fork = require ('child _ Process'). fork;
// Fork returns the sub-process object n
Var n = fork ('./child. js ');
// Process event message
N. on ('message', function (m ){
// Receives the message sent by the sub-process
Console. log ('got message: '+ m );
});

// Send a message to the sub-process
N. send ({hello: 'World '});

Sub-Process

The Code is as follows:


// Child. js
// Process event message
Process. on ('message', function (m ){
Console. log ('got message: '+ m );
});

// Process has the send method, which is used to send messages to the parent process.
Process. send ({foo: 'bar '});

Note that the send method here is synchronous, so it is not recommended to send a large amount of data (you can use pipe instead, see: http://nodejs.org/api/all.html#child_process_child_process_spawn_command_args_options for details ).
In special cases, the cmd attribute value in a message contains the NODE _ prefix (for example, {cmd: 'node _ foo'} message ), therefore, this message will not be submitted to the message event (but internalMessage event), and they will be used internally by the Node.

The prototype of the send method is:

The Code is as follows:


Send (message, [sendHandle])

Here, sendHandle (handle) can be used for sending:

1.net. Native, Native C ++ TCP socket or pipeline
2.net. Server, TCP Server
3.net. Socket, TCP socket
4. dgram. Native, Native C ++ UDP socket
5. dgram. Socket, UDP socket

When sending sendHandle, instead of directly sending JavaScript objects (and finally sending them as JSON strings), other processes can use this file descriptor to restore the corresponding objects.

Now let's look at an example:

Parent Process

The Code is as follows:


// Parent. js
Var fork = require ('child _ Process'). fork;

Var n = fork ('./child. js ');

Var server = require ('net'). createServer ();
Server. listen (7000, function (){
// Send the TCP server to the sub-process
N. send ('server', server );
}). On ('connection', function (){
Console. log ('Connection-parent ');
});

Sub-Process

The Code is as follows:


Process. on ('message', function (m, h ){
If (m = 'server '){
H. on ('connection', function (){
Console. log ('Connection-child ');
});
}
});

Access this program through port 7000. The output may be connection-parent or connection-child. The sub-process and the parent process listen to port 7000 at the same time. Generally, listening to the same port by multiple processes causes an EADDRINUSE exception. In this case, different processes use the same file descriptor, at the underlying layer of Node, the SO_REUSEADDR option is set for the socket when listening to the port, which enables the socket to be reused between different processes. When multiple processes listen to the same port, the file descriptor can only be used by one process at a time. These processes use socket in preemptible mode.

Cluster Module

The cluster module is added to v0.8 of Node. The cluster module can easily build a group of processes that listen to the same port on a physical machine. Example:

The Code is as follows:


Var cluster = require ('cluster ');
Var http = require ('http ');
Var numCPUs = require ('OS'). cpus (). length;

// Check whether the process is a master Process
If (cluster. isMaster ){
For (var I = 0; I <numCPUs; ++ I)
// Generate a new worker process (only the master process can be called)
Cluster. fork ();

Cluster. on ('eg', function (worker, code, signal ){
Console. log ('worker' + worker. process. pid + 'died ');
});
} Else {
Http. createServer (function (req, res ){
Res. writeHead (200 );
Res. end ('Hello world \ n ');
}). Listen (8000 );
}

We call the listen method in the worker process, and the listening request will be passed to the master process. If the master process already has a server being monitored that meets the requirements of the worker Process, the handle of this server will be passed to the worker. If it does not exist, the master process will create one, then pass handle to the worker process.

For more details about cluster documentation: http://www.nodejs.org/api/cluster.html

Related Article

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.