0

我正在尝试对 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()
4

1 回答 1

1

您只需要在 suite.add 的 fn 属性中移动大写字母函数,如下所示:

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()
于 2018-12-06T14:20:16.703 回答