Created
February 19, 2012 16:22
-
-
Save topliceanu/1864502 to your computer and use it in GitHub Desktop.
Stream downloader of web resources, based on mikeal's request, but processed first through zlib if necessary
This file contains 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
var request = require('request'); | |
var zlib = require('zlib'); | |
// A two-way passthrough Stream, made by @felixge | |
// https://github.com/felixge/node-passthrough-stream/blob/master/lib/passthrough_stream.js | |
var PassthroughStream = function () { | |
this.writable = true; | |
this.readable = true; | |
} | |
util.inherits(PassthroughStream, streams.Stream); | |
PassthroughStream.prototype.write = function(data) { | |
this.emit('data', data); | |
}; | |
PassthroughStream.prototype.end = function() { | |
this.emit('end'); | |
}; | |
PassthroughStream.prototype.destroy = function() { | |
this.emit('close'); | |
}; | |
// returns a Readable Stream from the resource, unzipping it if necessary | |
var requestGzip = function (requestOpts) { | |
var gzipHeaders = ['application/x-gzip', 'application/gzip']; | |
var req = request( requestOpts ); | |
var out = new PassthroughStream(); | |
req.on( 'response', function (res) { | |
if (gzipHeaders.indexOf( res.headers['content-type'] ) !== -1) { | |
return req.pipe(zlib.createGunzip()).pipe(out); | |
} | |
else { | |
return req.pipe(out); | |
} | |
}); | |
return out; | |
}; | |
// module api | |
module.exports = requestGzip |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment