Created
October 24, 2013 11:49
-
-
Save psi-4ward/7135840 to your computer and use it in GitHub Desktop.
Express example using busboy stream to GridFS
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 uploader = function(req, res) { | |
var busboy = new Busboy({ headers: req.headers }); | |
busboy.on('file', function(fieldname, stream, filename, encoding, contentType) { | |
var pStream = pauseStream(); // use pause stream to have time to open the GridStore | |
stream.pipe(pStream.pause()); | |
console.log('POST ' + req.originalUrl + ' File: '+ filename + ' Field: ' + fieldname); | |
cntProcessingFiles++; | |
new GridStore(db, null, filename , 'w', {content_type:contentType}).open(function(err, gridFile) { | |
if(err) console.log(err); | |
gridFile.on('close', function() { | |
gridFile.close(function(err, data) { | |
cntProcessingFiles--; | |
// do something with the gridfile | |
}); | |
}); | |
}); | |
pStream.pipe(gridFile); | |
pStream.resume(); | |
}); | |
}); | |
// form error (ie fileupload-cancel) | |
busboy.on('error', function(err) { | |
console.error(err); | |
res.send(500, 'ERROR', err); | |
}); | |
// all uploades finished | |
function end() { | |
// wait until all files are finished | |
if(cntProcessingFiles > 0) { | |
setTimeout(end, 200); | |
return; | |
} | |
if(res.finished) return; | |
res.send('all done'); | |
} | |
busboy.on('end', end); | |
// start parsing the HTTP-POST upload | |
req.pipe(busboy); | |
}; | |
app.post('/upload', uploader); |
@tk2, this should be defined like this:
var pauseStream = require('pause-stream');
Please don't forget to install this module first, or put this package as a dependency in your package.json file.
;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, was looking to do something similar.
Where is line#6 defined?
var pStream = pauseStream(); // use pause stream to have time to open the GridStore