0

I have a (somewhat weird) writable stream that I need to convert to a transform stream.

The writable stream, normally, sits at the end of a pipe chain and emits custom events once it has collected enough data for its output. I want it to go in the middle so I can pipe it to another writeStream, i.e:

    readStream.pipe(writeStreamToConvert).pipe(finalWriteStream);

What I done is the following and it works.

    const through2 = require('through2')


    var writeStreamToConvert = new WriteStreamToConvert();

    return through2.obj(function (chunk, enc, callback) {

        writeStreamToConvert.write(chunk)

        // object is the event emitted from the writestream
        writeStreamToConvert.on('object', (name, obj ) => {
            this.push(JSON.stringify(obj, null, 4) + '\n')
        });            

        callback()
    })

This works fine, does not seem to leak memory and is fairly quick. However node gives me a warning:

Warning: Possible EventEmitter memory leak detected. 11 object listeners added. Use emitter.setMaxListeners() to increase limit

So I am a little bit curious if this is the correct way of converting writestreams?

4

1 回答 1

0

事件处理程序最好放置在 Transform 流构造函数中。由于through2不支持这种初始化,您需要直接使用节点的流 API。

.on()目前,正在为写入through2流的每个对象添加一个新的事件处理程序(它永远不会被删除——这就是工作方式)。这就是发生警告的原因。

于 2017-07-10T20:14:31.247 回答