Benjin
Benjin

Reputation: 2409

Executing a shell script, printing output as it happens, and blocking until it's done?

I have a script written in JS that gets executed in Node (not a website, not an electron app; just node myscript.js in a terminal. Part of that script is executing a series of other (shell) scripts sequentially, and printing the output from those scripts as it happens.

I've tried two approaches:

const execSync = require('child_process').execSync;

for (const argItemin list) {
  console.log(execSync('myscript.bat ' + argItem, {encoding: 'utf-8'}));
}
const exec = require('child_process').exec;

for (const argItem in list) {
  const execution = exec('myscript.bat ' + argItem);
  execution.stdout.on('data', function (data) { console.log(data); });
}

The first approach executes and prints everything synchronously, but the output gets written after the each myscript.bat execution completes rather than as myscript.bat prints it out.

The second approach prints things as they happen, but because there's nothing blocking until each execution completes, the output is a jumbled mess.

How do I block on the child process of the second approach until the script has finished executing to get the best of both worlds? Thanks!

Upvotes: 1

Views: 179

Answers (1)

Benjin
Benjin

Reputation: 2409

Turns out I wanted

const execSync = require('child_process').execSync;

for (const argItemin list) {
  console.log(execSync('myscript.bat ' + argItem, {stdio: 'inherit'}));
}

Upvotes: 1

Related Questions