Last active
December 15, 2015 13:09
-
-
Save narqo/5265413 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @fileOverview [Node.js zlib module](http://nodejs.org/docs/v0.8.22/api/zlib.html) tests | |
* with `'accept-encoding': 'gzip'` http request | |
*/ | |
var http = require('http'), | |
zlib = require('zlib'), | |
rqopts = { | |
host : 'api.twitter.com', | |
path : '/1/trends/1.json', | |
headers: { 'accept-encoding': 'gzip,*' } | |
}; | |
function onResStream(res) { | |
console.log('\nUsing streams'); | |
res | |
.pipe(zlib.createGunzip()) | |
.pipe(process.stdout); | |
} | |
function onResBuffer(res) { | |
var buf = []; | |
res | |
.on('data', function(chunk) { | |
buf.push(chunk); | |
}) | |
.on('end', function() { | |
zlib.gunzip(Buffer.concat(buf), function(err, data) { | |
console.log('\nUsing buffer'); | |
if(err) { | |
console.log(err.message); | |
return; | |
} | |
console.log(data.toString()); | |
}); | |
}); | |
} | |
function onResStrings(res) { | |
var buf = ''; | |
res | |
.on('data', function(chunk) { | |
buf += chunk; | |
}) | |
.on('end', function() { | |
zlib.gunzip(buf, function(err, data) { | |
console.log('\nUsing strings'); | |
if(err) { | |
console.log(err.message); | |
return; | |
} | |
console.log(data.toString()); | |
}); | |
}); | |
} | |
function onResPiped(res) { | |
var gzip = zlib.createGunzip(); | |
res.pipe(gzip); | |
var buf = ''; | |
gzip | |
.on('data', function(chunk) { | |
buf += chunk; | |
}) | |
.on('end', function() { | |
console.log('\nUsing streams with pipe'); | |
console.log(buf + ''); | |
}); | |
} | |
http.get(rqopts, onResStream); | |
http.get(rqopts, onResBuffer); | |
http.get(rqopts, onResStrings); | |
http.get(rqopts, onResPiped); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment