Child Process NodeJS

1
2
3
4
5
6
//child.js - Simulate a long running process

setTimeout(function(){
console.log("Child Process " + process.argv[1] + " executed." );
//console.dir(process)
}, 10000);

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//master_spawn.js

var child = require('child_process');

var inter = setInterval(function(){
console.log("Main is running.....");
}, 1000);

var childProcess = child.spawn('node', ['child.js']);

childProcess.stdout.on('data', function (data) {
console.log('stdout: ' + data);
clearInterval(inter);
});
childProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
clearInterval(inter);
});
childProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//master_exec.js

var child = require('child_process');

var inter = setInterval(function(){
console.log("Main running.....");
}, 1000);

var childProcess = child.exec('node child.js', function(err, stdout, stderr){
if (err) {
console.log(err.stack);
console.log('Error code: '+err.code);
console.log('Signal received: '+err.signal);
}
console.log('stdout: ' + stdout);
console.log('stderr: ' + stderr);

clearInterval(inter);

childProcess.on('exit', function (code) {
console.log('Child process exited with exit code '+code);
});
});
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var child = require('child_process');

var inter = setInterval(function(){
console.log("Master running.....");
}, 1000);

var childProcess = child.fork('node', ['child.js']);

childProcess.stdout.on('data', function (data) {
console.log('stdout: ' + data);
clearInterval(inter);
});
childProcess.stderr.on('data', function (data) {
console.log('stderr: ' + data);
clearInterval(inter);
});
childProcess.on('close', function (code) {
console.log('child process exited with code ' + code);
});