我想将子进程的stdout / stderr流式传输到文件和父进程。
说我有这个:
const cp = require('child_process');
const fs = require('fs');
const fd = fs.openSync('bar.log','a');
const child = cp.spawn('node', [ 'foo.js' ], {
cwd: __dirname,
stdio: [ 'ignore', fd, fd ]
});
// using stdio array above I send stdout/stderr to log file
// but I would still like to receive stdout/stderr to this process so I can do something else with it
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
child.stdout.on('data', function (d) {
console.log('stdout => ', d);
});
child.stderr.on('data', function (d) {
console.log('stderr => ', d);
});
如果你运行它,它会给我这个错误:
child.stdout.setEncoding('utf8');
^
TypeError: Cannot read property 'setEncoding' of null
at Object.<anonymous> (/Users/Olegzandr/WebstormProjects/oresoftware/suman/private/exp9.js:14:13)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.runMain (module.js:575:10)
at run (node.js:348:7)
at startup (node.js:140:9)
at node.js:463:3
它的含义是,如果没有为stdout或stderr选择'pipe',那么该子进程的stdout / stderr将不会被传递给父进程。因此没有定义child.stdout和child.stderr ......
但是如果我想将stdout / stderr传递给父文件和文件呢?
我必须这样做:
const cp = require('child_process');
const fs = require('fs');
const child = cp.spawn('node', [ 'foo.js' ], {
cwd: __dirname,
stdio: [ 'ignore', 'pipe', 'pipe' ]
});
// using stdio array above I send stdout/stderr to log file
// but I would still like to receive stdout/stderr to this process so I can do something else with it
child.stdout.setEncoding('utf8');
child.stderr.setEncoding('utf8');
const strm = fs.createWriteStream('bar.log');
child.stdout.pipe(strm); //new code
child.stderr.pipe(strm); //new code
child.stdout.on('data', function (d) {
console.log('stdout => ', d);
});
child.stderr.on('data', function (d) {
console.log('stderr => ', d);
});
或者还有另一种方法可以做到这一点我还没见过?