簡體   English   中英

"Node.js 如何將 gzip 流通過管道傳輸到 writestream"

[英]Node.js how to pipe gzip stream to writestream

我似乎無法讓它工作。 我想將一些數據寫入 gzip 流,然后將 gzip 流通過管道傳輸到文件寫入流。 然后我想在文件完成寫入后調用一個函數。 我目前有:

  var gz = zlib.createGzip()
               .pipe(fs.createWriteStream(gz_path));

  gz.write(data);

  gz.on('error', function(err){
    console.log("wtf error", err);
  });

  gz.on('finish', function(){
    console.log("write stream is done");
    dosomething();
  });

嘗試

var zlib = require('zlib');
var stream = require('stream');
var util = require('util');
var fs = require('fs');

var gz = zlib.createGzip();

function StringifyStream(){
    stream.Transform.call(this);

    this._readableState.objectMode = false;
    this._writableState.objectMode = true;
}
util.inherits(StringifyStream, stream.Transform);

StringifyStream.prototype._transform = function(obj, encoding, cb){
    this.push(JSON.stringify(obj));
    cb();
};


var data = "some data in here";

var rs = new stream.Readable({ objectMode: true });
rs.push(data);
rs.push(null);


rs.pipe(new StringifyStream())
  .pipe(gz)
  .pipe(fs.createWriteStream('test.gz'))
  .on('error', function(err){
    console.log("wtf error", err);
  })
  .on('finish', function(){
  console.log("write stream is done");
  // dosomething();
});

我的例子:

async function run(){

var zlib = require('zlib');
var fs = require("fs");

var gz = zlib.createGzip();
gz.on('error', function(err){    console.log(err.stack);   });
// gz.on('finish', function() {    console.log("finished compression, now need to finish writing...");   });

var f = fs.createWriteStream('test.txt.gz');
f.on('error', function(err){    console.log(err.stack);       });
f.on('finish', function() {    console.log("Write success.");   });

gz.pipe(f);

// if stream.write returns false need to wait for drain,
// for example using await for a promise in an async function, or maybe run the callback on drain
if(!gz.write('test','utf-8'))
  await new Promise( (resolve,reject)=> gz.once('drain', resolve) )

gz.end();

console.log("Compress zip file success.");

}

run();

問題中的代碼有 3 個問題

  • 管道返回它的參數,而不是被調用的對象
  • 需要結束流,所以它會將數據寫入輸出
  • 最好在使用之前設置事件

// needded for code in question to run:
function dosomething(){

}
var gz_path="test.txt.gz"
var data="test"


//corrected code

var fs = require("fs");
var zlib = require('zlib');

// pipe retuns its argument, the folowing is correct:
// var f = zlib.createGzip().pipe(fs.createWriteStream(gz_path));

var gz = zlib.createGzip();

gz.pipe(fs.createWriteStream(gz_path));

// it helps to setup events before they fire  
gz.on('error', function(err){
    console.log("wtf error", err);
});

gz.on('finish', function(){
    console.log("write stream is done");
    dosomething();
});

gz.write(data);

// need to end stream for data to be written
gz.end()

管道的順序可能是問題所在。 我能夠通過在createGzip之前讓createGzip來解決這個createWriteStream 例如:

import Readable from "stream";
import zlib from "zlib";
import fs from "fs";

Readable.from([data])
   .pipe(zlib.createGzip())
   .pipe(fs.createWriteStream(`filePath.gzip`))
   .on("error", (error) => {
      // handle error
   })
   .on("finish", () => {
      // handle success
   })
import { createReadStream, createWriteStream } from 'fs'
import { createGzip } from 'zlib'

const filename = yourFile
// opens the file as a readable stream
createReadStream(filename)
   .pipe(createGzip())
   .pipe(createWriteStream(`${filename}.gz`))
   .on('finish', () => console.log('File compressed'))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM