Search code examples
node.jsnpmstdoutchild-process

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?


Solution

  • 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