Member-only story

Child Processes in Node.js

habtesoft
2 min readMar 30, 2023

--

Child processes in Node.js allow you to run other programs or scripts as separate processes. This can be useful for running CPU-intensive tasks or for running scripts that may crash or hang. Child processes also enable you to communicate between multiple processes and share data between them.

Not a Medium member? Read this article here

There are three types of child processes in Node.js:

  • child_process.spawn() - launches a new process and allows communication with it through pipes.
  • child_process.exec() - launches a new process and buffers the output.
  • child_process.fork() - launches a new Node.js process and allows communication with it through IPC (Inter-Process Communication).

Using child_process.spawn()

The child_process.spawn() method launches a new process and allows communication with it through pipes. Here's an example:

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}`);
});

--

--

habtesoft
habtesoft

Written by habtesoft

Passionate JavaScript developer with a focus on backend technologies. Always eager to connect and learn. Let’s talk, https://buymeacoffee.com/habtesoftat

No responses yet