I am trying to unzip a text file using Zlib library in node.js, but i get unexpected end of file error, when piping the files’s Readstream content towards a Gunzip object, here is my snippet:
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);
});
The greet.txt has some random text in it, and all the files used are already created in the directory, however an error event is triggered when the last line reaches
All node
operations are asynchronous, so you have to listen for finish
event.
readable.pipe(gZip).pipe(writableGz)
.on('finish', function () { // finished
console.log('Done. Now you can start reading.');
});
Here is a working code:
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) // extract file
.on("error", function (e) {
console.log("error, " + e);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With