Node.js multi-process
We all know that Node.js is single-threaded mode, but it is used to handle concurrent event-driven, which will help us create multiple sub-processes on multi-core cpu system, which improves performance.
Each child is always with three flow objects: child.stdin, child.stdout and child.stderr. They may share the stdio stream parent process, or it can also be steered independent stream object.
Node provides child_process modules to create a child process, by:
exec - child_process.exec use Run child process, the child process output buffer, and the output of the child process is returned in the form of a callback function parameters.
spawn - child_process.spawn using the specified command-line parameters to create a new process.
fork - child_process.fork is spawn () special form for the module running in the child, such as fork ( './ son.js') corresponds to spawn ( 'node', [ ' ./son.js' ]).The difference is the spawn method, fork in between the parent and child process, establish a communication conduit for communication between processes.
exec () method
child_process.exec use Run child process, the child process output buffer, and the output of the child process is returned in the form of a callback function parameters.
The syntax is as follows:
child_process.exec(command[, options], callback)
parameter
Parameters are as follows:
command: String, the command to run, the parameters separated by spaces
options: objects can be:
- The current working directory cwd, string, the child process
- env, the object of the key environmental variables
- encoding, string, character encoding (default: 'utf8')
- shell, string, to execute the command Shell (default: on UNIX is
/bin/sh
, as in Windowscmd.exe
, Shell should be able to identify the-c
switch in UNIX, or/s /c
in Windows. in Windows, the command line parsing be compatiblecmd.exe
) - timeout, digital, timeout (default: 0)
- maxBuffer, digital, the maximum buffer in stdout or stderr are allowed to exist (binary), so if the child will be killed beyond (default: 200 * 1024)
- killSignal, string end signal (default: 'SIGTERM')
- uid, digital, set the user ID of the process
- gid, digital, set process group ID
callback: callback function has three arguments error, stdout and stderr.
exec () method returns the maximum buffer, and wait for the end of the process, a one-time return the contents of the buffer.
Examples
Let's create two js files support.js and master.js.
support.js file code:
console.log("进程 " + process.argv[2] + " 执行。" );
master.js file code:
const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var workerProcess = child_process.exec('node support.js '+i, function (error, stdout, stderr) { if (error) { console.log(error.stack); console.log('Error code: '+error.code); console.log('Signal received: '+error.signal); } console.log('stdout: ' + stdout); console.log('stderr: ' + stderr); }); workerProcess.on('exit', function (code) { console.log('子进程已退出,退出码 '+code); }); }
Implementation of the above code, the output is:
$ node master.js 子进程已退出,退出码 0 stdout: 进程 1 执行。 stderr: 子进程已退出,退出码 0 stdout: 进程 0 执行。 stderr: 子进程已退出,退出码 0 stdout: 进程 2 执行。 stderr:
spawn () method
child_process.spawn using the specified command-line parameters to create a new process, syntax is as follows:
child_process.spawn(command[, args][, options])
parameter
Parameters are as follows:
command: the command to run
args: Array string parameter array
options Object
- Cwd String current working directory of the child process
- env Object environment variable key-value pairs
- stdio Array | stdio configuration String subprocess
- detached Boolean This child will become a process group leader
- uid Number to set the user ID of the process
- gid Number set process group ID
spawn () method returns the stream (stdout & stderr), used in the process to return large amounts of data. Once the process started when the spawn () began to receive a response.
Examples
Let's create two js files support.js and master.js.
support.js file code:
console.log("进程 " + process.argv[2] + " 执行。" );
master.js file code:
const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var workerProcess = child_process.spawn('node', ['support.js', i]); workerProcess.stdout.on('data', function (data) { console.log('stdout: ' + data); }); workerProcess.stderr.on('data', function (data) { console.log('stderr: ' + data); }); workerProcess.on('close', function (code) { console.log('子进程已退出,退出码 '+code); }); }
Implementation of the above code, the output is:
$ node master.js stdout: 进程 0 执行。 子进程已退出,退出码 0 stdout: 进程 1 执行。 子进程已退出,退出码 0 stdout: 进程 2 执行。 子进程已退出,退出码 0
fork method
child_process.fork is a special form of spawn () method for creating processes, syntax is as follows:
child_process.fork(modulePath[, args][, options])
parameter
Parameters are as follows:
modulePath: String, to be run in a child process module
args: Array string parameter array
options: Object
- Cwd String current working directory of the child process
- env Object environment variable key-value pairs
- execPath String create a child process of the executable file
- String parameter array execArgv Array child's executable file (default: process.execArgv)
- If silent Boolean
true
, the child'sstdin
,stdout
andstderr
will be linked to the parent process, otherwise, they will be inherited from the parent process. (Default:false
) - uid Number to set the user ID of the process
- gid Number set process group ID
The returned object in addition to all the methods have ChildProcess instance, there is a built-in communication channel.
h3> ExamplesLet's create two js files support.js and master.js.
support.js file code:
console.log("进程 " + process.argv[2] + " 执行。" );
master.js file code:
const fs = require('fs'); const child_process = require('child_process'); for(var i=0; i<3; i++) { var worker_process = child_process.fork("support.js", [i]); worker_process.on('close', function (code) { console.log('子进程已退出,退出码 ' + code); }); }
Implementation of the above code, the output is:
$ node master.js 进程 0 执行。 子进程已退出,退出码 0 进程 1 执行。 子进程已退出,退出码 0 进程 2 执行。 子进程已退出,退出码 0