Skip to content

Instantly share code, notes, and snippets.

@chirag04
Created December 12, 2013 14:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chirag04/7928997 to your computer and use it in GitHub Desktop.
Save chirag04/7928997 to your computer and use it in GitHub Desktop.
express-busboy.js
var BusBoy = require('busboy'),
fs = require('fs'),
path = require('path');
var RE_MIME = /^(?:multipart\/.+)|(?:application\/x-www-form-urlencoded)$/i;
// options will have limit and uploadDir.
exports = module.exports = function(options){
return function multipart(req, res, next) {
if (req.method === 'GET'
|| req.method === 'HEAD'
|| !hasBody(req)
|| !RE_MIME.test(mime(req))) {
return next();
}
var busboy = new BusBoy({
headers: req.headers,
limits: {
fileSize: (options.limit || 1) * 1024 * 1024
}
});
req.files = req.files || {};
req.body = req.body || {};
busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
var filePath = path.join(options.uploadDir, filename);
file.on('limit', function() {
var err = new Error('File size too large.');
err.status = 413;
next(err);
});
file.on('end', function () {
req.files[fieldname] = {
type: mimetype,
encoding: encoding,
name: filename,
path: filePath
};
});
file.pipe(fs.createWriteStream(filePath));
});
busboy.on('field', function (fieldname, val) {
req.body[fieldname] = val;
});
busboy.on('end', function () {
next();
});
req.pipe(busboy);
}
};
function hasBody(req) {
var encoding = 'transfer-encoding' in req.headers,
length = 'content-length' in req.headers
&& req.headers['content-length'] !== '0';
return encoding || length;
}
function mime(req) {
var str = req.headers['content-type'] || '';
return str.split(';')[0];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment