'use strict'; // Reads a request body as text, and refuses one that is too big, so a huge upload cannot use up the server's memory. function readBody(req, max = 2e6) { return new Promise((ok, no) => { const c = []; let n = 0, done = false; req.on('data', d => { if (done) return; n += d.length; if (n > max) { done = true; c.length = 0; const e = new Error('That is too large'); e.status = 413; no(e); return; } c.push(d); }); req.on('end', () => { if (!done) ok(Buffer.concat(c).toString()); }); req.on('error', e => { if (!done) no(e); }); }); } module.exports = { readBody };