我有两个程序:
process.stdin.pipe(process.stdout);
我将程序#1输出传送到程序#2。
如果程序#1产生长输出并终止,程序#2在完成打印输出之前终止。
a.js
:
let index = 0;
let output = '';
while (index < 1000000) {
output += ' ' + (index++);
}
console.log(output);
throw new Error('test');
b.js
:
process.stdin.pipe(process.stdout);
试验:
node a.js | b.js
b.js
程序仅生成a.js
输入的部分输出。
您可以使用上面的代码片段进行测试。似乎是最新node版本的一致行为。
如何在源程序终止时捕获整个程序管道输出?
要在CLI中复制:
node --eval "let index = 0; let output = ''; while (index < 1000000) { output += ' ' + (index++); } console.log(output); throw new Error('test');" | node --eval 'process.stdin.pipe(process.stdout);'
请注意,最后一个数字不是999999(在我的系统上总是12773),而是序列中间的一些数字。
使用process.stdout.write
代替console.log
不会改变行为。
进一步检查后,似乎可以使用cat
复制相同内容。
node --eval "let index = 0; let output = ''; while (index < 1000000) { output += ' ' + (index++); } console.log(output); throw new Error('test');" | cat
是否可以从接受输入的程序的角度解决问题?