Easiest Example of spawn | exec | fork | execFile | child_process in node js


Introduction

As we know node js is single-threaded which is great in selective cases like I/O operations, but after some point in time, we need other threads to work for us to distribute load.in that case we can make use of the child process and create new threads but that’s just one example we can use child process in multiple ways. For now, let’s break down the word child process 

Child Process 

node js main_process and child_process relation
        as we can see here in the diagram we have a parent process followed by 4 child_process if any child process is created to balance the load then in that case if any process failed at run time then the remaining three processes will take over its load. that's the reason mainly we use the child process to make sure of the high availability of our service.

Child 

Child must have parents. in node js main thread plays the role of parent and whichever process we call inside it. its child of the main thread.

Process

The process is nothing but an operation. When we hit command in a terminal, cmd, or shell it creates a new process. Whenever we click on any application icon it opens up the application User Interface behind the scene new process gets spawn. Every operation in machine is processes.

What is child_process

        The child process is node js native module ( native module is the module which comes along with node js installation it doesn’t require installation). This module helps us to create a new process for our application you can run .bat file or .exe file using this. you can hit Linux commands and stream the output etc.
        spawn() ,exec() ,fork(), execFile()  all these methods have asynchronous alternative which is recommended to use. otherwise, you may block your main thread which will block your entire application I am sure no one wants that.

node js child process types

The diagram is pretty self-explanatory but still, I will try to explain more basically, child_process allows us to create a new process using four different ways. 

Use Cases of child_process

  • a child_process can be useful in situations when you want some extra information about your system such as remaining ram in your pc, processor status, active connections, etc. in that case we can simply write exec() or spawn() command to hit command and get output.
  • if you are creating a desktop application using electron js and you want to start a new application from your application you can simply use execFile() and start that application.


1) spawn()

spawn executes the command in the same shell in which it has to spawn it streams the output until it completely gets executes or an error occurs you can access that stream by subscribing to its events such as stdout , stderr.

const { spawn } = require('child_process');
const ls = spawn('ls', ['-lh', '/usr']);

ls.stdout.on('data', (data) => {
  console.log(`stdout: ${data}`);
});

ls.stderr.on('data', (data) => {
  console.error(`stderr: ${data}`);
});

ls.on('close', (code) => {
  console.log(`child process exited with code ${code}`);
});
in the above example, we have created a new process using spawn as we know spawn streams data we can access that stream by stdout.

2) exec()

  • exec() creates a new shell and then executes a command inside it. 
  • the output is in buffer format.
Note: 

const { exec, spawn } = require('child_process');
exec('my.bat', (err, stdout, stderr) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(stdout);
});

// Script with spaces in the filename:
const bat = spawn('"my script.cmd"', ['a', 'b'], { shell: true });
// or:
exec('"my script.cmd" a b', (err, stdout, stderr) => {
  // ...
});

3) execFile()

const { execFile } = require('child_process');
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});

4) fork()

  • it returns the child process.
  • we can send messages between process back and forth.
  • each process is independent carries separate memory and separate instance.
const { execFile } = require('child_process');
const child = execFile('node', ['--version'], (error, stdout, stderr) => {
  if (error) {
    throw error;
  }
  console.log(stdout);
});


Note: use child process wisely because if it's not used correctly it might block your main thread.

Conclusion 

    hence we learned that the child process allows us to create a process in multiple ways we saw how to create a process with examples.

References: nodejs.org

Post a Comment

0 Comments