i would like to limit the request size for an upload in the following case (simplified):
app = Express();
router = Express.Router();
router.use('/upload', (req, res, next) => {
const writeStream = fs.createWriteStream('filename');
req.pipe(writeStream);
});
app.use(router);
As you can see, no form or similar is used (no way to change this). Therefore, the data is provided as a raw data stream.
As I could not find any existing modules for this case (body-parser does not work for this case, raw-body can also not be used as the stream should be left untouched), my current approach would be to use the following code as a middleware for express:
function(req, res, next) {
if (req.headers['content-length'] > limit) {
res.set("Connection", "close");
res.status(413).end();
return;
}
let received = 0;
req.on('data', (chunk) => {
received += chunk.length;
if (received > limit) {
res.set("Connection", "close");
res.status(413).end();
}
})
next();
})
Is there any better way to do this? Is there any existing npm package that can do this job?