How to pipe one readable stream into two writable streams at once in Node.js?

前端 未结 3 1310
轻奢々
轻奢々 2020-12-05 13:29

The goal is to:

  1. Create a file read stream.
  2. Pipe it to gzip (zlib.createGzip())
  3. Then pipe the read stream of zlib output to:

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-05 13:56

    I found that zlib returns a readable stream which can be later piped into multiple other streams. So I did the following to solve the above problem:

    var sourceFileStream = fs.createReadStream(sourceFile);
    // Even though we could chain like
    // sourceFileStream.pipe(zlib.createGzip()).pipe(response);
    // we need a stream with a gzipped data to pipe to two
    // other streams.
    var gzip = sourceFileStream.pipe(zlib.createGzip());
    
    // This will pipe the gzipped data to response object
    // and automatically close the response object.
    gzip.pipe(response);
    
    // Then I can pipe the gzipped data to a file.
    gzip.pipe(fs.createWriteStream(targetFilePath));
    

提交回复
热议问题