Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to spawn a new process in NodeJS and redirect stderr to stdout?

Tags:

bash

node.js

I need to spawn a new process in NodeJS. Its stderr should be redirected to its stdout (the same as 2>&1 in bash).

proc.js

var child_process = require('child_process');

var opt = {stdio: ['ignore', 'pipe', 'pipe']};
var proc = child_process.spawn('./myscript', [], opt);
proc.stderr.pipe(proc.stdout);
proc.stdout.on('data', function (buf) {
    console.log('stdout', buf.toString());
});
proc.on('error', function (...args) {
    console.log('error', args);
});
proc.on('exit', function (code, signal) {
    console.log('exit', code, signal);
});
proc.on('close', function (code, signal) {
    console.log('close', code, signal);
});

myscript

#!/bin/bash

echo 111
echo 222 >&1
echo 333 >&2
echo 444

Unfortunately this doesn't work. There is no 333 in the output:

stdout 111
222
444

exit 0 null
close 0 null
like image 440
vbarbarosh Avatar asked Nov 19 '16 20:11

vbarbarosh


1 Answers

I think your problem is you are piping the child (proc) stderr to it own stdout, rather than your own stdout. proc.stdout is a source, not a sink, so it can't take input from another pipe.

Maybe what you want is, instead of:

proc.stderr.pipe(proc.stdout);

this:

proc.stderr.pipe(process.stdout);

process.stdout is your parent process stdout, which is a sink, so it can take proc.stderr, which is a source.

like image 66
Jim B. Avatar answered Oct 23 '22 02:10

Jim B.