I am using execSync
to execute a shell script within a javascript script
const { execSync } = require('child_process');
const shell = (cmd) => execSync(cmd, { encoding: 'utf8' });
shell('node jest');
When I run jest
from my terminal, I see each step in the console as the script is ongoing.
When I run shell(script)
, I only see the whole results at the end of the script.
What should I do to output in live the execution of a script using execSync
?
After some research I found the proper method.
child_process.exec() is "synchronously asynchronous", meaning although the .exec is asynchronous, it waits for the child process to end and tries to return all the buffered data at once
child_process.spawn() returns an object with stdout and stderr stream
Hence I opted to use spawn
and created
const shellAsync = (cmd) => {
const script = spawn(cmd);
script.stdout.on('data', (data) => {
console.log(`${data}`);
});
script.stderr.on('data', (data) => {
console.error(`${data}`);
});
script.on('close', (code) => {
console.log(`child process exited with code ${code}`);
});
};