a blog for those who code

Monday 25 August 2014

Difference between fork, spawn and exec in Nodejs

In this post we will show you what is the difference between fork, spawn and exec in Nodejs.In Nodejs it is possible to stream data through a child's stdin, stdout and stderr in a fully non-bloking way.

We can create a child process using require ('child_process').spawn() or require('child_process').fork() or require('child_process').exec(). So, you might ask that then whats the difference between these processes.

Spawn


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.

child_process.spawn(command, [args], [options])

Suppose you have a file named YourJs.js as
console.log("Process " + process.argv[2]);

fs = require('fs');
process = require('child_process');
var ls = process.spawn('node','YourJs.js');
ls.stdout.on('data', function(data)) {
 console.log('stdout: ' + data);
});

When you run the above peice of code, you will get an output as stdout: Process 0

Fork


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.

fs = require('fs');
process = require('child_process');
var ls = process.fork('YourJs.js');
ls.stdout.on('data', function(data)) {
 console.log('stdout: ' + data);
});

When you run the above peice of code, you will get an output as stdout: Process 0

Exec


require('child_process').exec() returns a buffer from the child process. The default buffer size is 200k. It is asynchronous, but it waits for the child process to end and tries to return all the buffered data at once. If your return data from the child process is greater than 200k then you will get maxBuffer exceeded.

fs = require('fs');
process = require('child_process');
var ls = process.exec('node YourJs.js', function (error, stdout, stderr) {
if(error)
console.log(error.code);
});

When you run the above peice of code, you will get an output as stdout: Process 0

Please Like and Share the Blog, if you find it interesting and helpful.

1 comment:

  1. About spawn() ...In this no new V8 instance will be created...

    How about if spawn a node process? also no new V8 instance will be created?

    A bit confused.

    ReplyDelete