raspberryGPIOhtmlserver/node_modules/connect/lib/middleware/limit.js
node_modules/connect/lib/middleware/limit.jsRaw
1
2/*!
3 * Connect - limit
4 * Copyright(c) 2011 TJ Holowaychuk
5 * MIT Licensed
6 */
7
8/**
9 * Module dependencies.
10 */
11
12var utils = require('../utils'),
13 brokenPause = utils.brokenPause;
14
15/**
16 * Limit:
17 *
18 * Limit request bodies to the given size in `bytes`.
19 *
20 * A string representation of the bytesize may also be passed,
21 * for example "5mb", "200kb", "1gb", etc.
22 *
23 * connect()
24 * .use(connect.limit('5.5mb'))
25 * .use(handleImageUpload)
26 *
27 * @param {Number|String} bytes
28 * @return {Function}
29 * @api public
30 */
31
32module.exports = function limit(bytes){
33 if ('string' == typeof bytes) bytes = utils.parseBytes(bytes);
34 if ('number' != typeof bytes) throw new Error('limit() bytes required');
35 return function limit(req, res, next){
36 var received = 0
37 , len = req.headers['content-length']
38 ? parseInt(req.headers['content-length'], 10)
39 : null;
40
41 // self-awareness
42 if (req._limit) return next();
43 req._limit = true;
44
45 // limit by content-length
46 if (len && len > bytes) return next(utils.error(413));
47
48 // limit
49 if (brokenPause) {
50 listen();
51 } else {
52 req.on('newListener', function handler(event) {
53 if (event !== 'data') return;
54
55 req.removeListener('newListener', handler);
56 // Start listening at the end of the current loop
57 // otherwise the request will be consumed too early.
58 // Sideaffect is `limit` will miss the first chunk,
59 // but that's not a big deal.
60 // Unfortunately, the tests don't have large enough
61 // request bodies to test this.
62 process.nextTick(listen);
63 });
64 };
65
66 next();
67
68 function listen() {
69 req.on('data', function(chunk) {
70 received += Buffer.isBuffer(chunk)
71 ? chunk.length :
72 Buffer.byteLength(chunk);
73
74 if (received > bytes) req.destroy();
75 });
76 };
77 };
78};