Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js - ZLIB Gunzip returns empty file

Tags:

node.js

zlib

I'm just testing ZLIB of Node.js but quickly facing strange results. Here is my script (inspired from the Node.js manual example http://nodejs.org/api/zlib.html#zlib_examples):

var zlib = require('zlib') ,
    fs = require('fs') ,
    inp1 = fs.createReadStream('file.txt') ,
    out1 = fs.createWriteStream('file.txt.gz') ,
    inp2 = fs.createReadStream('file.txt.gz') ,
    out2 = fs.createWriteStream('output.txt') ;

inp1.pipe(zlib.createGzip()).pipe(out1);   /* Compress to a .gz file*/
inp2.pipe(zlib.createGunzip()).pipe(out2); /* Uncompress the .gz file */

In this example, and before executing the script, I created a file called file.txt and I fullfill it with a sample text (say a Lorem Ipsum).

The previous script creates successfully the .gz file, that I can unzip from the finder (I'm on Mac OSX), but the uncompressed output.txt file is empty.

Why? Do you have any idea?

like image 436
htaidirt Avatar asked Mar 20 '13 16:03

htaidirt


1 Answers

Node streams are asynchronous, so both of your streams will run at the same time. That means that when you initially open inp2 that file.txt.gz is empty, because the other write stream hasn't added anything to it yet.

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

var src = 'file.txt',
    zip = 'file.txt.gz',
    dst = 'output.txt';

var inp1 = fs.createReadStream(src);
var out1 = fs.createWriteStream(zip);

inp1.pipe(zlib.createGzip()).pipe(out1);

out1.on('close', function(){
  var inp2 = fs.createReadStream(zip);
  var out2 = fs.createWriteStream(dst);
  inp2.pipe(zlib.createGunzip()).pipe(out2);
})
like image 96
loganfsmyth Avatar answered Oct 23 '22 05:10

loganfsmyth