I spawn some command synchronously and want two things:
- Pipe its stdout to process.stdout.
- Save the stdout into variable.
I’ve written this code:
var spawnSync = require('child_process').spawnSync;
var result = spawnSync('ls', [ '-l', '-a' ]);
var savedOutput = result.stdout;
console.log(String(savedOutput));
So, I store stdout in savedOutput variable — it’s ok, and log it out. But I haven’t pipe it to stdout. If the spawned process is long and write strings one by one, I see empty screen a long time, and at the end I see whole stdout of process.
I’ve add options for piping:
var spawnSync = require('child_process').spawnSync;
var result = spawnSync('ls', [ '-l', '-a' ], {
stdio: [ 'ignore', 1, 2 ]
});
var savedOutput = result.stdout;
console.log(String(savedOutput));
Stdout of spawned process is piped to stdout — it’s ok. But result.stdout is empty.
I’ve tried to use stream:
var spawnSync = require('child_process').spawnSync;
var stream = require('stream');
var grabber = new stream.Writable();
grabber._write = function(chunk, enc, done) {
console.log('Chunk:');
console.log(String(chunk));
done();
};
var result = spawnSync('ls', [ '-l', '-a' ], {
stdio: [ 'ignore', grabber, 2 ]
});
... but get an error:
internal/child_process.js:795
throw new TypeError('Incorrect value for stdio stream: ' +
^
TypeError: Incorrect value for stdio stream: Writable
If I set grabber.fd = 2
, I don’t get an error, but child stdout pipes to stdout instead of grabber.
So. How to save child stdout into variable and pipe it to stdout in the same time?