require('child_process').spawn() starts sending back data from the child process in a stream as soon as the child process starts executing. When you run this command, it send a system command that will run on its own process rather than executing code within your node process. In this no new V8 instance will be created and only one copy of the node module will be active on the processor. It is used when you want the child process to return large amount of data to Node.
Example:
child.js
spawn.js
require('child_process').fork() is a special instance of spawn thats runs a new instance of the V8 engine. Which actually means you are creating multiple workers running on the same Node code base for different task.
fork.js
Example:
child.js
| var i = 0; | |
| setInterval(function() { | |
| if (i++ % 2) { | |
| console.log('I\'m the child!'); | |
| } else { | |
| console.error('I\'m the child!'); | |
| } | |
| }, 1500); |
spawn.js
| var spawn = require('child_process').spawn; | |
| var child = spawn('node', ['child.js']); | |
| child.stdout.on('data', function (data) { | |
| console.log('stdin:', data.toString()); | |
| }); | |
| child.stderr.on('data', function (data) { | |
| console.log('child stderr: ', data.toString()); | |
| }); | |
| child.on('close', function (code) { | |
| if (code !== 0) { | |
| console.log('child process exited with code ' + code); | |
| } | |
| }); | |
| setTimeout(function() { | |
| throw new Error('ZEPELE'); | |
| }, 5000); |
require('child_process').fork() is a special instance of spawn thats runs a new instance of the V8 engine. Which actually means you are creating multiple workers running on the same Node code base for different task.
fork.js
| var fork = require('child_process').fork; var child = fork('child.js'); | |
| child.on('close', function (code) { | |
| if (code !== 0) { | |
| console.log('child process exited with code ' + code); | |
| } | |
| }); | |
| setTimeout(function() { | |
| throw new Error('ZEPELE'); | |
| }, 5000); |