如何在源程序终止时捕获整个程序管道输出?

时间:2018-05-11 10:35:53

标签: node.js

我有两个程序:

  1. 打印长输出并在产生输出后直接崩溃。
  2. 只需执行process.stdin.pipe(process.stdout);
  3. 即可

    我将程序#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输入的部分输出。

    您可以使用上面的代码片段进行测试。似乎是最新版本的一致行为。

    如何在源程序终止时捕获整个程序管道输出?

    要在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
    

    是否可以从接受输入的程序的角度解决问题?

0 个答案:

没有答案