如何根据第一个块中的数据将流重定向到其他流?

How to redirect a stream to other stream depending on data in first chunk?

我正在使用 Busboy 处理多部分形式的文件。简化版的过程如下所示:

file.pipe(filePeeker).pipe(gzip).pipe(encrypt).pipe(uploadToS3)

filePeeker 是一个直通流(使用 trough2 构建)。此双工流执行以下操作:

在第一个块的前四个字节之后,我知道该文件是否是一个 zip 文件。如果是这种情况,我想将文件重定向到一个完全不同的流。在新流中,压缩文件将被解压缩,然后使用与原始文件相同的概念单独处理。

我怎样才能做到这一点?

原始过程: file.pipe(filePeeker).if(!zipFile).pipe(gZip).pipe(encrypt).pipe(uploadToS3)

解压过程 file.pipe(filePeeker).if(zipFile).pipe(streamUnzip).pipeEachNewFile(originalProcess).

谢谢 //迈克尔

有用于此的模块,但基本思想是在条件的早期推送到另一个可读流和 return。为它写一个转换流。

var Transform = require("stream").Transform;
var util = require("util");
var Readable = require('stream').Readable;

var rs = new Readable;
rs.pipe(unzip());

function BranchStream () {
    Transform.call(this);
}
util.inherits(BranchStream, Transform);

BranchStream.prototype._transform = function (chunk, encoding, done) {
     if (isZip(chunk)) {
         rs.push(chunk);
         return done()
     }
     this.push(doSomethingElseTo(chunk))
     return done()
}