1

In Node.js, I can run a shell command with a program that looks like the following

const { exec } = require("child_process")
exec('/path/to/long-running-commnd', function(err, stdout, stderr) {
  // function will get here with a fully populated stdout
  // when command
  console.log(stdout)
})

That is, the exec function accepts a shell command, will run it, and when the command finishes running it will call the second callback argument.

This works, but if there's a long running command that prints output to console as it finishes sub-tasks (something like a long running build script), my node program will not print out anything until the entire command is run.

Does Node.js offer an API that would allow me to run a shell process and receive output as that output is written to stdout rather than waiting until the entire command is done?

Alana Storm
  • 164,128
  • 91
  • 395
  • 599
  • Does this answer your question? [Exec : display stdout "live"](https://stackoverflow.com/questions/10232192/exec-display-stdout-live) – Jason Lee Feb 16 '22 at 13:32

1 Answers1

2

https://nodejs.org/api/child_process.html

const { spawn } = require('node: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}`);
});