Skip to content

Instantly share code, notes, and snippets.

@danielbeardsley
Created May 6, 2011 16:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danielbeardsley/959268 to your computer and use it in GitHub Desktop.
Save danielbeardsley/959268 to your computer and use it in GitHub Desktop.
Simple nodejs interface to the gzip utility found on every *nix system
/* Provides a simple interface to the gzip executable found on the system, should work in all *nix environments.
* Keep in mind that this spawns a process, so don't go using for every request, only use it in non-time-sensitive places
* Thanks mostly go to 3Rd-Eden who created the original code in a pull-request to Socket.IO-node
*/
var child_process = require('child_process');
module.exports.gzip = function(buffer, callback){
var gzip = child_process.spawn('gzip', ['-9'])
, buffers = []
, stdErr = false;
gzip.stdout.on('data', function(chunk){
buffers.push(chunk);
});
gzip.stderr.on('data', function(){
stdErr = true;
buffers.length = 0;
});
gzip.on('exit', function(){
var length = 0
, index = 0
, content;
if (buffers.length && !stdErr ){
buffers.forEach(function(buff){
length += buff.length;
});
content = new Buffer(length);
buffers.forEach(function(buff, i){
buff.copy(content, index, 0);
index += buff.length;
});
buffers.length = 0;
return callback(null, content);
}
return callback(stdErr);
});
gzip.stdin.write(buffer);
gzip.stdin.end();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment