我像这样产生一个子进程:
const n = cp.spawn('bash');
n.stdout.pipe(process.stdout);
n.stderr.pipe(process.stderr);
我正在寻找一个转换流,以便我可以在子进程的每一行的开头添加类似“[子进程]”的内容,因此我知道标准输入输出来自子进程而不是父进程。
所以它看起来像:
const getTransformPrepender = function() : Transform {
return ...
}
n.stdout.pipe(getTransformPrepender('[child]')).pipe(process.stdout);
n.stderr.pipe(getTransformPrepender('[child]')).pipe(process.stderr);
有谁知道是否有这样的现有转换包或如何编写一个?
我有这个:
import * as stream from 'stream';
export default function(pre: string){
let saved = '';
return new stream.Transform({
transform(chunk, encoding, cb) {
cb(null, String(pre) + String(chunk));
},
flush(cb) {
this.push(saved);
cb();
}
});
}
但我担心它在边缘情况下不起作用 - 一个块突发可能不包括整行(对于很长的行)。
看起来这个问题的答案在这里:https ://strongloop.com/strongblog/practical-examples-of-the-new-node-js-streams-api/
但有这个附录: https ://twitter.com/the1mills/status/886340747275812865