节点,创建一个流对象,该对象内部已经有一些流

时间:2018-09-22 03:11:40

标签: node.js stream pipe

我想在nodejs中创建一个可读可写的流Objetc,该流Objetc在内部简单地连接多个流对象,以允许对项目进行某种程度的抽象。

最优雅的方法是什么?

这里有一些代码示例来演示我的尝试。

function main(transformerType) {
    var readStream = new ReadStream();
    var writeStream = new WriteStream();
    var transformerStream;

    if (transformerType === "a") {
        transformerStream = getATransformer();
    }
    else {
        transformerStream = getDefaultTransformer();
    }

    readStream.pipe(transformerStream).pipe(writeStream);
}

function getDefaultTransfromer() {
    return new DefaultTransformerStream();
}

function getATransformer() {
    var xStream = new LibraryXStream();
    var yStream = new LibraryYStream();
    xStream.pipe(yStream);

    // This next line won't work
    // I want to return a stream-object that has a function pipe which calls pipe from yStream
    // and when getting piped to will pipe into xStream
    // sort of a wrapper that has xStream and yStream already connected
    return xxx?;
}

1 个答案:

答案 0 :(得分:0)

我至少在下面的测试代码中创建了TransformerWrapper类,该类似乎可以解决该问题。当然,在该简单示例中,所有这些流都可以在一条线上连接在一起。但是,目标是找到一种方法,以将几个似乎是一个可读写流对象的连接流返回给调用函数。

如果有人发现更好的东西,我将不胜感激。

const stream = require("stream");

class TransformerWrapper extends stream.Transform {
    constructor (transformers) {
        super();
        var i = 1;

        this.firstTransformer = transformers[0];
        this.lastTransformer = transformers[transformers.length-1];

        this.lastTransformer.on("data", (chunk) => {
            this.push(chunk);
        });

        for (; i < transformers.length; i++) {
            transformers[i-1].pipe(transformers[i]);
        }
    }
    _write(chunk, encoding, callback) {
        this.firstTransformer.write(chunk, encoding, callback);
    }
}

class TransformerA extends stream.Transform {
    _transform(chunk, encoding, callback) {
        this.push(chunk + '_A');
        callback();
    }   
}

class TransformerB extends stream.Transform {
    _transform(chunk, encoding, callback) {
        this.push(chunk + '_B');
        callback();
    }   
}

class Writer extends stream.Writable {
    _write(chunk, encoding, callback) {
        console.log("writer", chunk.toString());
        callback();
    }   
}

var transformerA = new TransformerA();
var transformerB = new TransformerB();

var transformerWrapper = new TransformerWrapper([transformerA, transformerB]);
transformerWrapper.pipe(new Writer());
transformerWrapper.write("foo");
transformerWrapper.write("bar");