In node when I try and spawn a child process and then listen to stdout stream data and send it to process.stdout ansi colours are stripped:
// Will not preserve tty colors
const cp = spawn(procExec, ['--production'])
cp.stdout.on('data', (buf) => {
// can manipulate buf
process.stdout.write(buf)
});
cp.stderr.on('data', (buf) => {
// can manipulate buf
process.stderr.write(buf)
});
// Also will not preserve tty colors
const cp = spawn(procExec, ['--production'])
cp.stdout.pipe(process.stdout);
cp.stderr.pipe(process.stderr);
Looking through the node docs and the standard solution is to use the various possibilities for the stdio option:
const cp = spawn('ls', ['-l'], {
stdio: 'inherit'
})
or
const cp = spawn('ls', ['-l'], {
stdio: [0,1,2]
})
or
const cp = spawn('ls', ['-l'], {
stdio: [process.stdin,process.stdout,process.stderr]
})
This WILL preserve ANSI colors in a terminal.
Normally this is fine however this means it is impossible to manipulate the output of the stream before it is sent to process.stdout or process.stderr.
a. Why does piping to child_process.stdout to process.stdout strip ANSI colors? Is it the same reason that listening to the data event does the same?
b. How can I both manipulate manipulate the output (ie. change the text) of the stream WHILST keeping the colors at the same time?