htaidirt htaidirt - 1 year ago 122
Node.js Question

Node.js - ZLIB Gunzip returns empty file

I'm just testing ZLIB of Node.js but quickly facing strange results. Here is my script (inspired from the Node.js manual example

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
and I fullfill it with a sample text (say a Lorem Ipsum).

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

Why? Do you have any idea?

Answer Source

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);


out1.on('close', function(){
  var inp2 = fs.createReadStream(zip);
  var out2 = fs.createWriteStream(dst);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download