Search code examples
node.jsstdio

Send the stdout of spawnSync to another spawnSync stdin


How do I emulate linux's | (pipe) in a node.js app to pipe the stdout of a command to the stdin of the next command. Both commands are being spawned with spawnSync.

This (pseudo code) works as expected in the commandline:

$ command1 -arg1 file | command2 arg2
> someoutput

But this does not:

const spawnSync = require('child_process').spawnSync;

const c1Spawn = spawnSync('command1', ['arg1', 'file']);
const c2Spawn = spawnSync('command2', ['arg2'], { input: c1Spawn.output });

const someoutput = c2Spawn.output;

Solution

  • I believe I found the answer by using input: c1Spawn.stdout instead of output as the in for the second command.

    const spawnSync = require('child_process').spawnSync;
    
    const c1Spawn = spawnSync('command1', ['arg1', 'file']);
    const c2Spawn = spawnSync('command2', ['arg2'], { input: c1Spawn.stdout });
    
    const someoutput = c2Spawn.output;