Node.js runs in single-threaded, event-driven mode, which is good for improving performance via multiple child process.
Each child process has three stream objects:
child.stdin
child.stdout
child.stderr
All these three stream objects may share their parent’s stdio
, or set to use their own stream object independently.
Node.js offers child_process
module to create new child process:
exec
–child_process.exec
use child process to execute shell command, and buffer the output for callback. This means theexec
will buffer the whole returned value in buffer, usually you should limit the buffer in 200k, if not, the process will exit withError: maxBuffer exceeded
.spawn
–child_process.spawn
use command line to create new process. spawn will return a stream object withstdout
andstderr
. We can usestdout
stream to read the data returned from child process.stdout
has event handles likedata
,end
. You can usespawn
when a large data will returned from child process.fork
–child_process.fork
is thespawn
in special mode(specifynode
to run the command).fork('./son.js')
equals tospawn('node', ['./son.js'])
. Different fromspawn
,fork
will build a message pipe between main and child process.
exec
1 | const exec = require('child_process').exec |
spawn
1 | const spawn = require('child_process').spawn |
fork
1 | // parent.js |