Nodejs simple getting started tutorial (3): process, nodejs simple
Although Node itself has multiple threads, the 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:
Copy codeThe 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
Copy codeThe 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
Copy codeThe 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:
Copy codeThe 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
Copy codeThe 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
Copy codeThe 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:
Copy codeThe 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
What is the relationship between JSON, JS, and NODEJS?
They are completely different in nature.
JavaScript is a JavaScript language and an explanatory programming language.
JSON is JavaScript Object Notation, which indicates the expression of objects in JavaScript language. It is often used for data transmission (similar to XML) and often replaces XML in AJAX.
NodeJS is a server platform that can run server scripts written in JavaScript on the server.
Note: In JS, functions are itself an object. Therefore, functions can be used as parameters not unique to NodeJS. To be precise, NodeJS uses Google V8 interpreter of Chrome browser to explain JS.
To sum up:
JS is a programming language.
JSON is a data format (no logic, only data)
NodeJS is a software (JS server running environment)
By the way, HTML is derived from XML (HTML is an XML), but changes to adapt to its specific role. HTML (XML) and JSON are the same data expression language, strictly speaking, the logic does not include only data.
What is node. js event-driven programming?
Nodejs is a single-process, single-thread, but based on the powerful driving force of V8 and the event-driven model, nodejs has very high performance, in addition, it is not difficult to achieve multi-core or multi-process (a large number of third-party modules are already available to implement this function ).
Here we will not introduce the specific application code of nodejs, but will introduce the event-driven programming.
Dan York introduces two typical event-driven instances.
The first example is about seeing a doctor.
When you go to the United States to see a doctor, you need to fill in a large number of forms, such as insurance, personal information, and so on. The traditional thread-based system, the receptionist calls you, you need to fill out these forms at the front-end. You are standing and filling out the form, while the receptionist is sitting and watching you fill out the form. You cannot allow the receptionist to receive the next customer unless you complete your business.
To make the system run faster, only a few receptionists need to be added, and the labor cost needs to be increased a lot.
In the event-based system, when you arrive at the window, you need to fill in some additional forms, not just hanging up a number. The receptionist will give you the form and pen, you can fill in a seat and then go back to him. You go back and fill out the form, and the receptionist starts to receive the next customer. You didn't block the receptionist's service.
The second example is a fast food restaurant ordering.
In the thread-based approach, before you arrive at the counter, give your order to the cashier or give the cashier a direct order, then wait until the food you want is ready for you. The cashier cannot receive the next person unless you get the food and leave. It's easy to receive more customers! Add more cashiers!
Of course, we know that fast food restaurants do not actually work like this. They are actually event-driven, so that the Cashier is more efficient. As long as you give the order to the cashier, someone has begun preparing your food and the cashier is collecting the money, you are standing aside and the cashier has begun to receive the next customer. In some restaurants, you may even get a number. If your food is ready, call your number to ask you to pick it up at the counter. The key point is that you have not blocked the next customer's order request. When the food you order is prepared, a person may make an action (a waiter calls your order number and you hear your number be called for food). In the programming field, we call this callback function ).
On the contrary, Node. Js uses the event-driven model. When the web server receives a request, it closes the request and processes it, And then serves the next web request. When the request is completed, it is put back into the processing queue. When it reaches the beginning of the queue, this result is returned to the user. This model is highly efficient and highly scalable, because webserver keeps receiving requests without waiting for any read/write operations. (This is also called non-blocking IO or event-driven IO ).
Consider the following process:
You can use a browser to access "/about.html" on the nodejs server"
The nodejs server receives your request and calls a function to read the file from the disk.
During this time, nodejs webserver will serve subsequent web requests.
When the file is read, a callback function is inserted into the service queue of nodejs.
When nodejs webserverruns this function, renderreturns the about.html page to your browser.
It seems to have saved several microseconds, but this is very important! Especially for web servers that require a large number of users.