简体   繁体   中英

Use node script to start child process, capture child stdout, and kill child on close

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?

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

It sure can! Have a look on this question for further explanation and alternatives.

If you only want to print the "logs" on your terminal, this should work:

require("child_process").spawn('npm', ['start'], {
  cwd: process.cwd(),
  detached: true,
  stdio: "inherit"
})

If you really need to pass stdout to myVar , you could do something like:

const child = require('child_process')

let myVar = ''

child.spawn('npm', ['start'], function(err, stdout, stderr) { 
  // this will be invoked when the process terminates
  myVar = stdout
  console.log(stdout)
})

Hope that helps! Cheers

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM