Dung (Donny) Nguyen

Senior Software Engineer

Child Processes in Node.js

In Node.js, child processes allow us to execute external programs or scripts from within our Node.js application. This is useful for various tasks, such as:

Node.js provides three primary methods to create child processes:

1. child_process.spawn()

const { spawn } = require('child_process');

const childProcess = spawn('python', ['script.py']);

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

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

childProcess.on('close', (code) => {
    console.log(`child process exited with code ${code}`);
});

Explanation:

2. child_process.exec()

const { exec } = require('child_process');

exec('ls -la', (error, stdout, stderr) => {
    if (error) {
        console.error(`error: ${error.message}`);
        return;
    }
    if (stderr) {
        console.error(`stderr: ${stderr}`);
        return;
    }
    console.log(`stdout: ${stdout}`);
});

Explanation:

3. child_process.fork()

const { fork } = require('child_process');

const childProcess = fork('child.js', ['arg1', 'arg2']);

childProcess.on('message', (message) => {
    console.log(`Message from child: ${message}`);
});

childProcess.send({ foo: 'bar' });

Explanation:

Choosing the Right Method:

By understanding these methods, we can effectively leverage child processes to enhance the capabilities of our Node.js applications.