-1

I would like to start a node-script called myScript.js, that starts a child process npm start, store the stdout of npm start into a global variable let myVar, and make sure that if the main program myScript.js is exited for any reason, the child process is killed as well. Nothing from the child's stdout should appear in the terminal window after ctr-c or similar.


My current solution does not kill on close:

const childProcess = require('child_process');

let myVar = ''

const child = childProcess.spawn('npm', ['start'], {
    detached: false
});

process.on('exit', function () {
    child.stdin.pause();
    child.kill();
});

child.stdout.on('data', (data) => {
    myVar = `${data}`
});

Can this be accomplished?

johann1301s
  • 343
  • 4
  • 19
  • The link you provided leads to "Page not found". – johann1301s Sep 08 '22 at 17:25
  • 1
    Sorry, typing on my phone. Sharing the link as text: https://stackoverflow.com/questions/25340875/nodejs-child-process-exec-disable-printing-of-stdout-on-console – Moa Sep 08 '22 at 17:59

1 Answers1

2

Small change, but I think that might look something like this:

const childProcess = require('child_process')

const child = childProcess.spawn('npm', ['start'], {shell:true});
var myVar = ''; child.stdout.setEncoding('utf8');
child.stdout.on('data', function(data) {
    myVar = data.toString(); 
});
child.on('close', function(exitcode) {
    // on the close of the child process, use standard output or maybe call a function
});

process.on('exit', function() {
    // I don't think pausing std.in is strictly necessary
    child.kill()
})

Further reading

JohnAlexINL
  • 615
  • 7
  • 15