我正在尝试使用node.js中的Zlib库解压缩文本文件,但是当我将文件的Readstream内容传递给Gunzip对象时,我得到意外的文件结束错误,这是我的代码段:
const fs = require('fs');
const zlib = require("zlib");
var readable = fs.createReadStream(__dirname + '/greet.txt');
var readableGz = fs.createReadStream(__dirname + '/greet.txt.gz');
var writableGz = fs.createWriteStream(__dirname + '/greet.txt.gz');
var gZip = zlib.createGzip();
var gUnZip = zlib.createGunzip();
readable.pipe(gZip).pipe(writableGz); // compress file
readableGz.pipe(gUnZip).on("error", function(e){ // uncompress file
console.log("error, " + e);
});
greet.txt中有一些随机文本,所有使用的文件都已在目录中创建,但是当最后一行到达时会触发错误事件
答案 0 :(得分:2)
所有node
操作都是异步的,因此您必须侦听finish
事件。
readable.pipe(gZip).pipe(writableGz).on('finish', function () { // finished
console.log('Done. Now you can start reading.');
});
这是工作代码:
const fs = require('fs');
const zlib = require("zlib");
var readable = fs.createReadStream('./greet.txt');
var writableGz = fs.createWriteStream('./greet.txt.gz');
var gZip = zlib.createGzip();
var gUnZip = zlib.createGunzip();
readable.pipe(gZip).pipe(writableGz).on('finish', function () { // finished
console.log('Done. Now you can start reading.');
var readableGz = fs.createReadStream('./greet.txt.gz');
readableGz.pipe(gUnZip).on("error", function (e) { // uncompress file
console.log("error, " + e);
});
});