Nodejs child_process spawn custom stdio
Asked Answered
D

1

14

I would like to use custom stream to handle child_process.spawn stdio.

For example

const cp = require('child_process');
const process = require('process');
const stream = require('stream');

var customStream = new stream.Stream();
customStream.on('data', function (chunk) {
    console.log(chunk);
});

cp.spawn('ls', [], {
    stdio: [null, customStream, process.stderr]
});

I get error Incorrect value for stdio stream.

There is documentation for child_process.spawn https://nodejs.org/api/child_process.html#child_process_options_stdio. It says for stdio options that it can take Stream object

Stream object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process.

I guess I'am missing this "refers to" part.

Dogged answered 23/1, 2016 at 18:41 Comment(0)
D
13

It seems to be a bug: https://github.com/nodejs/node-v0.x-archive/issues/4030 The customStream seems to be not ready when it's passed to spawn(). You can go around this issue easily:

const cp = require('child_process');
const stream = require('stream');

// use a Writable stream
var customStream = new stream.Writable();
customStream._write = function (data) {
    console.log(data.toString());
};

// 'pipe' option will keep the original cp.stdout
// 'inherit' will use the parent process stdio
var child = cp.spawn('ls', [], {
    stdio: [null, 'pipe', 'inherit'] 
});

// pipe to your stream
child.stdout.pipe(customStream);
Drillmaster answered 26/1, 2016 at 12:50 Comment(2)
Yes, this is something I am using on the end. ThanksDogged
While this is a good workaround, the actual problem is that stdio streams require an underlying file descriptor. Custom streams don't have that.Ameliaamelie

© 2022 - 2024 — McMap. All rights reserved.