4 * Copyright(c) 2011 TJ Holowaychuk
12 var createError = require('http-errors');
13 var deprecate = require('depd')('connect');
14 var parseBytes = require('bytes');
15 var utils = require('../utils');
16 var brokenPause = utils.brokenPause;
21 * Status: Deprecated. This middleware will be removed in Connect 3.0.
22 * If you still wish to use some type of limit middleware,
23 * you may be interested in:
25 * - [raw-body](https://github.com/stream-utils/raw-body)
27 * Limit request bodies to the given size in `bytes`.
29 * A string representation of the bytesize may also be passed,
30 * for example "5mb", "200kb", "1gb", etc.
33 * .use(connect.limit('5.5mb'))
34 * .use(handleImageUpload)
36 * @param {Number|String} bytes
41 module.exports = function limit(bytes){
42 if ('string' == typeof bytes) bytes = parseBytes(bytes);
43 if ('number' != typeof bytes) throw new Error('limit() bytes required');
45 return function limit(req, res, next){
47 , len = req.headers['content-length']
48 ? parseInt(req.headers['content-length'], 10)
52 if (req._limit) return next();
55 // limit by content-length
56 if (len && len > bytes) return next(createError(413));
62 req.on('newListener', function handler(event) {
63 if (event !== 'data') return;
65 req.removeListener('newListener', handler);
66 // Start listening at the end of the current loop
67 // otherwise the request will be consumed too early.
68 // Sideaffect is `limit` will miss the first chunk,
69 // but that's not a big deal.
70 // Unfortunately, the tests don't have large enough
71 // request bodies to test this.
72 process.nextTick(listen);
79 req.on('data', function(chunk) {
80 received += Buffer.isBuffer(chunk)
82 Buffer.byteLength(chunk);
84 if (received > bytes) req.destroy();
90 module.exports = deprecate.function(module.exports,
91 'limit: Restrict request size at location of read');