Question

I'm trying to run a child process to modify a file (in two steps) before reading the modified content from stdout. I'm trying to do this by using process substitution which works perfectly in bash but not when i try it from node.

This is kind of, what the command looks like..

var p = exec('command2 <(capture /dev/stdout | command1 -i file -) -',
function (error, stdout, stderr) {
   console.log(stderr);
});

stderr prints:

/bin/sh: -c: line 0: syntax error near unexpected token `('

What is the proper way of doing this in node?

Was it helpful?

Solution

I solved this by putting the commands in a shell script and calling the script from the node child process. I also needed to add the following to set bash in posix mode to allow process substitution:

set +o posix

There is probably a nicer way of doing this directly from within node but it did the job. Cheers!

OTHER TIPS

This is caused by bash running in posix mode when invoked as /bin/sh.

Invoking bash directly from /bin/bash avoids that:

child_process.execSync('diff <(curl a) <(curl b)', {shell: '/bin/bash'});

You can spawn a child_process with bash substitution in Node by invoking the sh command with the -c flag.

The sh command uses your default bash interpreter, and the -c flag asks the interpreter to read commands from within the string, Ie: $(echo $PATH). Additional flags are then passed to their normal positional references, such as: $0, $1, ect.

So an example might be:

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

const prg = 'sh',

    args = [
        '-c',
        'echo $($0 $1)',
        'ls', // $0
        '-la' // $1
    ],

    opts = {
        stdio: 'inherit'
    };

// Print a directory listing, Eg: 'ls -la'
const child = spawn(prg, args, opts);

you can have bash evaluate a command with bash -c 'command'. I've tested this and it works with process substitution and child_process.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top