Skip to content

Commit

Permalink
Removed finish event if file-size limit reached
Browse files Browse the repository at this point in the history
Also allowed limitHandler and abortOnLimit to exist simultaneously without headers already sent error.
Solves richardgirges#238.
  • Loading branch information
sliterok authored Oct 28, 2020
1 parent 1216f4f commit f0199f6
Showing 1 changed file with 11 additions and 6 deletions.
17 changes: 11 additions & 6 deletions lib/processMultipart.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,11 @@ module.exports = (options, req, res, next) => {

// Close connection with specified reason and http code, default: 400 Bad Request.
const closeConnection = (code, reason) => {
req.unpipe(busboy);
res.writeHead(code || 400, { Connection: 'close' });
res.end(reason || 'Bad Request');
if(!res.headersSent) {
req.unpipe(busboy);
res.writeHead(code || 400, { Connection: 'close' });
res.end(reason || 'Bad Request');
}
};

// Build multipart req.body fields
Expand Down Expand Up @@ -70,9 +72,11 @@ module.exports = (options, req, res, next) => {
// Reset upload timer in case of file limit reached.
uploadTimer.clear();
// Run a user defined limit handler if it has been set.
if (isFunc(options.limitHandler)) return options.limitHandler(req, res, next);
if (isFunc(options.limitHandler)) options.limitHandler(req, res, next);

// Close connection with 413 code and do cleanup if abortOnLimit set(default: false).
if (options.abortOnLimit) {
busboy.removeListener('finish', finishListener)
debugLog(options, `Aborting upload because of size limit ${field}->${filename}.`);
closeConnection(413, options.responseOnLimit);
cleanup();
Expand Down Expand Up @@ -130,7 +134,7 @@ module.exports = (options, req, res, next) => {
uploadTimer.set();
});

busboy.on('finish', () => {
function finishListener() {
debugLog(options, `Busboy finished parsing request.`);
if (options.parseNested) {
req.body = processNested(req.body);
Expand All @@ -147,7 +151,8 @@ module.exports = (options, req, res, next) => {
debugLog(options, `Error while waiting files flush: ${err}`);
next(err);
});
});
}
busboy.on('finish', finishListener);

busboy.on('error', (err) => {
debugLog(options, `Busboy error`);
Expand Down

0 comments on commit f0199f6

Please sign in to comment.