Search code examples
javascriptnode.jsspawngoogle-home

Capture input in the child process after spawn in node


I'm working on a small cli tool that can automatically deploy Google Home actions based on the projects that are setup in a directory.

Basically my script checks the directories and then asks which project to deploy. The actual command that should run is coming from Google's cli gactions

To run it with arguments I setup a spawned process in my node-script:

const { spawn } = require('child_process')
const child = spawn('./gactions', [
    'update',
    '--action-package',
    '<PATH-TO-PACKAGE>',
    '--project',
    '<PROJECT-NAME>'
])

child.stdout.on('data', data => {
    console.log(data)
}

However, the first time a project is deployed, the gactions cli will prompt for an authorization code. Running the code above, I can actually see the prompt, but the script won't proceed when actually entering that code.

I guess there must be some way in the child process to capture that input? Or isn't this possible at all?


Solution

  • Simply pipe all standard input from the parent process to the child and all output from the child to the parent.

    The code below is a full wrapper around any shell command, with input/output/error redirection:

    const { spawn } = require('child_process');
    var child = spawn(command, args);
    
    child.stdout.pipe(process.stdout);
    child.stderr.pipe(process.stderr);
    process.stdin.pipe(child.stdin);
    
    child.on('exit', () => process.exit())
    

    Note that if you pipe stdout you don't need handle the data event anymore.