使用Transform form single stream Node.js创建多个流

时间:2019-12-13 23:28:08

标签: javascript node.js stream es6-class nodejs-stream

我正在尝试转换来自Web套接字流的单个流。

我写了两个类,一个类从流中获取数据,然后我需要将数据通过管道传输到3个流中,然后将它们导出以使数据事件在导入该文件的其他文件中可用。

这是我创建类和对象并导出它们的代码。

// reading product ids in the form of array
const product_ids = require('../config').PRODUCT_IDS
const stream = require('stream');

class UnifiedStream extends stream.Transform {

    constructor() {
        super({
            objectMode: true,
            highWaterMark: 1
        });

    }
    _transform(chunk, encoding, callback) {

        this.push(chunk);
        callback()

    }
}

class FilterProducts extends stream.Transform {

    constructor(product_id) {

        super({
            readableObjectMode: true,
            writableObjectMode: true
        });
        this.product_id = product_id
    }
    _transform(chunk, encoding, callback) {
        console.log(this.product_id)
        if (chunk.product_id && chunk.product_id == this.product_id) {
            this.push(chunk);
            callback(null, callback)
        }
    }
}



let unified_stream = new UnifiedStream();

// here we are attaching the stream of objects with the 
product_ids.forEach(product_id => {

    let filter_product = new FilterProducts(product_id);
    unified_stream.pipe(filter_products)
    product_streams.push(
        filter_product
    )


})


module.exports.unified_stream = unified_stream
module.exports.product_streams = product_streams

这是我将数据发送到 unified_stream 的代码,但是第二部分没有数据。

let streams = require('./streams/streams')


connections.on('message', data => {

    // this where we get the strem and write to unified stream
    streams.unified_stream.write(data);
})

streams.product_streams[0].on("data", (data) => {
    console.log(data)
})

0 个答案:

没有答案