To spawn a new process in which you need unbuffered output (e.g. long-running processes which might print output over a period of time rather than printing and exiting immediately), use child_process.spawn().

This method spawns a new process using a given command and an array of arguments. The return value is an instance of [ChildProcess](<https://nodejs.org/dist/latest/docs/api/child_process.html#child_process_class_childprocess>), which in turn provides the stdout and stderr properties. Both of those streams are instances of [stream.Readable](<https://nodejs.org/dist/latest/docs/api/stream.html#stream_class_stream_readable>).

The following code is equivalent to using running the command ls -lh /usr.

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

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

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

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

Another example command:

zip -0vr "archive" ./image.png

Might be written as:

spawn('zip', ['-0vr', '"archive"', './image.png']);