Skip to content
Browse files

json parser middleware, use freelist

  • Loading branch information...
1 parent 574497b commit e4fe18d57eb5e2afd1539604ae219c47df5de3bb @chjj committed
Showing with 30 additions and 1 deletion.
  1. +30 −1 lib/json.js
View
31 lib/json.js
@@ -4,7 +4,8 @@
*/
var EventEmitter = require('events').EventEmitter
- , StringDecoder = require('string_decoder').StringDecoder;
+ , StringDecoder = require('string_decoder').StringDecoder
+ , FreeList = require('freelist').FreeList;
/**
* Parser
@@ -419,6 +420,34 @@ Parser.create = function(parser) {
module.exports = exports = Parser.create;
exports.Parser = Parser;
+exports.middleware = function() {
+ var parsers = new FreeList('parsers', 20, function() {
+ return Parser.create();
+ });
+ return function(req, res, next) {
+ if (req._json) return next();
+ req._json = true;
+
+ var type = req.headers['content-type'];
+ if (type && type.split(';')[0].trim() === 'application/json') {
+ var parser = parsers.alloc();
+
+ parser.on('error', function(err) {
+ req.socket.destroy();
+ next(err);
+ });
+
+ parser.on('end', function(data) {
+ parsers.free(parser);
+ req.body = data;
+ next();
+ });
+ } else {
+ next();
+ }
+ };
+};
+
/**
* Crude Test
*/

0 comments on commit e4fe18d

Please sign in to comment.
Something went wrong with that request. Please try again.