-main.js (file)
var {spawn, exec} = require('child_process');
// 'node' is an executable command (can be executed without a shell)
// uses streams to transfer data (spawn.stout)
var spawn = spawn('node', ['module.js']);
spawn.stdout.on('data', function(msg){
console.log(msg.toString())
});
// the 'node module.js' runs in the spawned shell
// transfered data is handled in the callback function
var exec = exec('node module.js', function(err, stdout, stderr){
console.log(stdout);
});
-module.js (basically returns a message every second for 5 seconds than exits)
var interval;
interval = setInterval(function(){
console.log( 'module data' );
if(interval._idleStart > 5000) clearInterval(interval);
}, 1000);
- the
spawn()
child process returns the message module data
every 1 second for 5 seconds, because the data is 'streamed'
- the
exec()
child process returns one message only module data module data module data module data module data
after 5 seconds (when the process is closed) this is because the data is 'buffered'
NOTE that neither the spawn()
nor the exec()
child processes are designed for running node modules, this demo is just for showing the difference, (if you want to run node modules as child processes use the fork()
method instead)