/

How to Spawn a Child Process with Node.js

How to Spawn a Child Process with Node.js

Learn how to spawn a child process with Node.js

Node.js provides the child_process module, which allows you to spawn child processes.

To get started, require the module and access the spawn function:

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

The spawn function takes two parameters. The first parameter is the command to run, and the second parameter is an array containing a list of options.

Here’s an example:

1
spawn('ls', ['-lh', 'test']);

In this case, the ls command is executed with two options: -lh and test. The result is a detailed output of the test file:

1
-rw-r--r-- 1 flaviocopes staff 6B Sep 25 09:57 test

The spawn() function call returns an instance of the ChildProcess class, which identifies the spawned child process.

Here’s a slightly more complicated example that shows how to watch the test file and run the ls -lh command whenever it changes:

1
2
3
4
5
6
7
8
9
'use strict';

const fs = require('fs');
const { spawn } = require('child_process');
const filename = 'test';

fs.watch(filename, () => {
const ls = spawn('ls', ['-lh', filename]);
});

There’s one more step to complete. To see the output of the child process, we need to pipe it to the main process. This can be done by calling the pipe() method on the stdout property of the child process:

1
2
3
4
5
6
7
8
9
10
'use strict';

const fs = require('fs');
const { spawn } = require('child_process');
const filename = 'test';

fs.watch(filename, () => {
const ls = spawn('ls', ['-lh', filename]);
ls.stdout.pipe(process.stdout);
});

Tags: Node.js, child process, spawn, command execution