It is well known that node. JS is based on a single-threaded model architecture, designed to deliver efficient CPU utilization, but cannot utilize multiple core CPUs, to address this problem, node. JS provides a child_process module that enables multi-core CPU utilization through multiple processes. The Child_process module provides four functions for creating sub-processes, namely spawn,exec,execfile and fork.
simple usage of 1.spawn functions
The Spawn function publishes a sub-process with the given command and only runs the specified program, and the parameters need to be given in the list. The following example:
- var child_process = require(' child_process ');
- var child = child_process. Spawn( command );
- Child. StdOut. On(' data ', function(data) {
- Console. Log(data);
- });
By executing the command to get the return result, we can get the standard output stream data.
simple usage of 2.exec functions
exec is also a function to create a child process, unlike the Spawn function it can directly accept a callback function as a parameter, the callback function has three parameters, namely, err, stdout, stderr, the basic use of the following methods:
- var child_process = require(' child_process ');
- Child_process. EXEC( command , function(err, stdout , stderr ) {
- Console. Log( stdout );
- });
The EXEC function can directly accept a callback function as a parameter, the callback function has three parameters, namely, err, stdout,stderr, very convenient to use directly,
simple usage of 3.execFile functions
The execfile function is similar to the EXEC function, but the execfile function is more streamlined because it can execute the specified file directly, using the following basic methods:
- var child_process = require(' child_process ');
- Child_process. ExecFile( file , function(err, stdout , stderr ) {
- Console. Log( stdout );
- });
ExecFile is similar to the parameters of spawn, and it is necessary to specify the commands and arguments to execute separately, but you can accept a callback function the same as the exec callback function.
simple usage of 4.fork functions
The fork function can run the node. JS module directly, so we can directly manipulate it by specifying the module path. Here's how to use it:
- var child_process = require(' child_process ');
- Child_process. Fork( modulepath );
This method is a special scenario for spawn (), which is used to derive the node process. In addition to all the methods that an ordinary childprocess instance has, the returned object also has a built-in communication channel.
node. JS (vii) Sub-process Child_process module