Created
May 6, 2011 16:18
-
-
Save danielbeardsley/959268 to your computer and use it in GitHub Desktop.
Simple nodejs interface to the gzip utility found on every *nix system
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
/* 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