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