Sometimes, we want to spawn child process and get terminal output live with Node.js.
In this article, we’ll look at how to spawn child process and get terminal output live with Node.js.
How to spawn child process and get terminal output live with Node.js?
To spawn child process and get terminal output live with Node.js, we can use the child_process
module’s spawn
method.
For instance, we write
const spawn = require('child_process').spawn;
const child = spawn('node ./commands/server.js');
let scriptOutput = "";
child.stdout.setEncoding('utf8');
child.stdout.on('data', (data) => {
console.log('stdout: ' + data);
data = data.toString();
scriptOutput += data;
});
child.stderr.setEncoding('utf8');
child.stderr.on('data', (data) => {
console.log('stderr: ' + data);
data = data.toString();
scriptOutput += data;
});
child.on('close', (code) => {
console.log('closing code: ' + code);
console.log('Full output of script: ', scriptOutput);
});
to call spawn
to run 'node ./commands/server.js'
.
Then we call child.stdout.on
with 'data'
to listen for stdout outputs.
In the function we pass into child.stdout.on
, we log the output data
with console.log
and append the data
to scriptOutput
after it’s converted to a string.
Likewise, we call child.stderr.on
to listen to stderr output by calling child.stderr.on
with 'data'
.
The callback is the same.
Finally, we call child.on
with 'close'
to get the exit code
when the child process finishes running.
Conclusion
To spawn child process and get terminal output live with Node.js, we can use the child_process
module’s spawn
method.