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.stdinchild.stdoutchild.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.execuse child process to execute shell command, and buffer the output for callback. This means theexecwill 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.spawnuse command line to create new process. spawn will return a stream object withstdoutandstderr. We can usestdoutstream to read the data returned from child process.stdouthas event handles likedata,end. You can usespawnwhen a large data will returned from child process.fork–child_process.forkis thespawnin special mode(specifynodeto run the command).fork('./son.js')equals tospawn('node', ['./son.js']). Different fromspawn,forkwill 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 |



