Skip to content
Related Articles

Related Articles

Save Article
Improve Article
Save Article
Like Article

Difference between spawn() and fork() methods in Node.js

  • Difficulty Level : Easy
  • Last Updated : 21 Oct, 2021

In this article, we will discuss the difference between spawn() and fork() methods in Node.js. Both are ways to create child processes in Node.js in order to handle increasing workloads.

Spawn() method: The spawn process initiates a command in a new process. We can pass the command as an argument to it. The result of the spawn function is a child process instance that implements EventEmitterAPI.Handlers for events can be attached or registered to the child instance created. Some of the events that can be attached or registered on that child instances are disconnect, error, close, and message, etc.

Parameters: This method accepts the following parameters.

  • command: It accepts commands to run as a string.
  • args: It is a list of string arguments. The default value is an empty array.
  • options: This options object can have various properties like stdio, uid, gid, shell, etc.
    • shell: Accepts a boolean value. If true, runs the command inside of a shell. The different shell can be specified as a string. The default value is false which implies no shell.

Return Value: It returns an instance of the child process.

  
 



Example: This is a very simple and general example of the use of spawn. We first required spawn by destructuring, then create a child process by passing arguments. Then register a stdout event on that child process.

 

Javascript




const { spawn } = require('child_process');
const child = spawn('dir', ['D:\\empty'], { shell: true });
 
child.stdout.on('data', (data) => {
  console.log(`stdout ${data}`);
});

Output:

Message sent from child.js is printing in file server.js due to the use of fork child process.

Difference between Spawn and Fork child process:

Spawn 

Fork

This starts sending data back to a parent process from the child process as soon as the child process starts executing.This does not send data automatically, but we can use a global module name process to send data from the child process and in the parent module, using the name of the child the process to send to the child process.
It creates a new process through command rather than running on the same node process.It makes several individual processes (child processes) but all of them run on the same node process as the parent.
In this, no new V8 instance is created.In this, a new V8 instance is created.
It is used when we want the child process to return a large amount of data back to the parent process.It is used to separate computation-intensive tasks from the main event loop.
My Personal Notes arrow_drop_up
Recommended Articles
Page :