Skip to content

Instantly share code, notes, and snippets.

@ErikAndreas
Last active December 20, 2015 10:59
Show Gist options
  • Save ErikAndreas/6119825 to your computer and use it in GitHub Desktop.
Save ErikAndreas/6119825 to your computer and use it in GitHub Desktop.
Node.js streaming upload (and no tmp file on disk) with Multiparty with pipe to gunzip
"use strict";
var multiparty = require('multiparty')
, http = require('http')
, util = require('util')
, zlib = require('zlib');
http.createServer(function(req, res) {
if (req.url === '/upload' && req.method === 'POST') {
var form = new multiparty.Form();
var gunzip = zlib.createGunzip();
var out = '';
form.on('part',function(part) {
if (part.filename) {
part.on('data', function(chunk) {
// plain file contents goes here
});
part.pipe(gunzip);
gunzip.on('data', function(data) {
// here we have un-gzipped data
out += data.toString();
});
gunzip.on('end', function() {
// our gzipped data is json, return it
res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8' });
console.log('gunzip done');
res.end(out);
});
}
});
form.on('error', function(err) {
console.log('fail ' + err);
});
form.on('progress',function(bytesReceived, bytesExpected) {
console.log(bytesReceived +'/'+ bytesExpected);
});
// will probably fire before gunzip end
form.on('close',function() {
console.log('form done');
});
// any form fields goes here
form.on('field',function(name,value) {
console.log(name+'='+value);
});
form.parse(req);
}
}).listen(3000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment