github.com/cloudcredo/cloudrocker@v0.0.0-20160108110610-1320f8cc2dfd/sample-apps/node/node_modules/logfmt/lib/body_parser.js (about) 1 2 /* 3 Module dependencies. 4 */ 5 6 /* 7 JSON: 8 9 Parse logplex request bodies, providing the 10 parsed object as `req.body`. 11 12 Options: none 13 14 @param content_type {String} use when Content-Type matches this string 15 @param parser {Function} parsing function takes String body and returns new body 16 @return {Function} 17 @api public 18 */ 19 20 exports = module.exports = function(options) { 21 var limit; 22 if (options == null) options = {}; 23 24 return function(req, res, next) { 25 if (req._body) return next(); 26 var is_mime = req.header('content-type') === options.contentType; 27 if (!is_mime) return next(); 28 req._body = true; 29 req.body = req.body || {}; 30 var buf; 31 buf = ""; 32 req.setEncoding("utf8"); 33 req.on("data", function(chunk) { 34 return buf += chunk; 35 }); 36 req.on("end", function() { 37 try { 38 var lines = [] 39 buf.trim().split("\n").forEach(function(line){ 40 lines.push(options.parser(line)) 41 }) 42 req.body = lines; 43 } catch (err) { 44 err.body = buf; 45 err.status = 400; 46 return next(err); 47 } 48 return next(); 49 }); 50 }; 51 };