Reputation: 22369
When you use execSync then you can specify stdio:
https://nodejs.org/api/child_process.html#child_process_options_stdio
Number five says that you can pass a Stream object:
- object - Share a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process. The stream's underlying file descriptor is duplicated in the child process to the fd that corresponds to the index in the stdio array. Note that the stream must have an underlying descriptor (file streams do not until the 'open' event has occurred).
However, I am unable to pass an object. I've tried:
const { PassThrough, Writable } = require('stream');
const pass = new PassThrough();
Which I found here:
https://nodejs.org/api/stream.html#stream_three_states
But I couldn't pass that as stdio: [..., stdout, ...] for execSync options method call.
require('child_process').execSync(command, options);
Anyone?
Upvotes: 1
Views: 2179
Reputation: 88
As it says -
a readable or writable stream that refers to a tty, file, socket, or a pipe with the child process
So, you cannot use any stream you like. I don't know the underlying reason however. Below is how you can make it work using a fs.createWriteStream. Note the 'open' event - that seems to be important, if not waiting for that event before invoking the childProcess.exec, you'll get an error.
const fs = require('fs')
const childProcess = require('child_process')
const stream = new fs.createWriteStream('out')
stream.on('open', function() {
childProcess.execSync('ls -la', {stdio:['ignore', stream, stream]})
})
As an alternative you can also pass a file descriptor to the stdio array entries. What I am personally also missing is the possibility to pass in any kind of streams, especially 'through' streams that would allow to tee the output to multiple sinks. As mentioned I don't know why this is - there might be a good reason for it. Hope someone else can provide more details.
Upvotes: 2