使用 Benchmark.js 测试转换流 (Node.js) 时出现问题

Problem during testing transform-streams (Node.js) with Benchmark.js

我正在尝试对 NodeJS 代码进行基准测试,但出现以下错误:

    events.js:167
    throw er; // Unhandled 'error' event
    ^

    Error [ERR_STREAM_WRITE_AFTER_END]: write after end
    at writeAfterEnd (_stream_writable.js:243:12)
    at Transform.Writable.write (_stream_writable.js:291:5)
    at ReadStream.ondata (_stream_readable.js:666:20)
    at ReadStream.emit (events.js:182:13)
    at addChunk (_stream_readable.js:283:12)
    at readableAddChunk (_stream_readable.js:264:11)
    at ReadStream.Readable.push (_stream_readable.js:219:10)
    at lazyFs.read (internal/fs/streams.js:181:12)
    at FSReqWrap.wrapper [as oncomplete] (fs.js:460:17)

    Emitted 'error' event at:
    at Transform.onerror (_stream_readable.js:690:12)
    at Transform.emit (events.js:182:13)
    at writeAfterEnd (_stream_writable.js:245:10)
    at Transform.Writable.write (_stream_writable.js:291:5)
    [... lines matching original stack trace ...]
    at lazyFs.read (internal/fs/streams.js:181:12)

我的代码可以独立运行,但不能与 Benchmark.js 一起运行。问题出在哪里? 似乎当 Benchmark.js 开始第二个测试时,它试图在一个关闭的文件上写入,但我看不出问题所在。

    const Benchmark = require('benchmark');
    const suite = new Benchmark.Suite;
    const fs = require('fs');
    const stream = require('stream');

    const uppercaser = new stream.Transform({
        transform: function (chunk, _, callback) {
            callback(null, chunk.toString().toUpperCase());
       }
    });

    suite.add('transform-streams', {
       defer: true,
       fn: function (deferred) {

            const readStream = fs.createReadStream('1.txt', {
               highWaterMark: 1024
            });
            const writeStream = fs.createWriteStream('write1.txt');

            readStream
               .pipe(uppercaser)
               .pipe(writeStream).on('finish', () => {
                   deferred.resolve();
                });
         }
    })
    .on('cycle', function (event) {
        console.log(String(event.target));
    }).on('complete', function () {
        console.log(this[0].stats)
    }).run()

你只需要在 suite.add 的 fn 属性中移动 uppercaser 函数,像这样:

suite.add('transform-streams', {
   defer: true,
   fn: function (deferred) {

       const uppercaser = new stream.Transform({
         transform: function (chunk, _, callback) {
           callback(null, chunk.toString().toUpperCase());
         }
       });

        const readStream = fs.createReadStream('1.txt', {
           highWaterMark: 1024
        });
        const writeStream = fs.createWriteStream('write1.txt');

        readStream
           .pipe(uppercaser)
           .pipe(writeStream).on('finish', () => {
               deferred.resolve();
            });
     }
})
.on('cycle', function (event) {
    console.log(String(event.target));
}).on('complete', function () {
    console.log(this[0].stats)
}).run()