Friday 19 October 2018

Node.js: child_process.spawn(command[, args][, options]): Spawns a new process

In my previous post, I explained how to execute a system command using exec() method. Spawn is also similar to exec method, only difference is, it is used for long running processes, where as exec is suitable for immediate response processes.

For example,

infinite.js
var interval_time_out = 500;
var count = 0;

/* Write some data to console for every 500 milliseconds */
var intervalRef = setInterval(function() {
    console.log('%d. Hi, I am here', ++count);
}, interval_time_out);

/* Whenever data is written to stdin of this process, exit the process*/
process.stdin.on('data', (data) => {
 console.log('stop event.........');
    process.exit(0);
});

HelloWorld.js
var spawn = require('child_process').spawn;

/* Execute a command and get the reference of child process */
var child_process1 = spawn('node', ['infinite.js']);

/* Whenever child process writes some data, it prints here */
child_process1.stdout.on('data', (data) => {
    console.log(`Received : ${data}`);
});

/* Whenever child process exits, this method is called */
child_process1.on('data', (data) => {
    console.log('Received close event!!!!!!!!');
});

/* Write some data to child process input stream after 5 seconds */
setTimeout(() => {
    child_process1.stdin.write("stop");
}, 5000);

HelloWorld.js file spwans a child process by executing ‘node inifinits.js’ script. Since spawn method return a reference to child process, you can receive the events.



Previous                                                 Next                                                 Home

No comments:

Post a Comment