-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?

2
  • The link you provided leads to "Page not found". Commented Sep 8, 2022 at 17:25
  • 1
    Sorry, typing on my phone. Sharing the link as text: stackoverflow.com/questions/25340875/… Commented Sep 8, 2022 at 17:59

1 Answer 1

2
+200

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

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.