Skip to content

fix: prevent file handle leak when maxFiles is exceeded#1068

Open
guoyangzhen wants to merge 1 commit intonode-formidable:masterfrom
guoyangzhen:master
Open

fix: prevent file handle leak when maxFiles is exceeded#1068
guoyangzhen wants to merge 1 commit intonode-formidable:masterfrom
guoyangzhen:master

Conversation

@guoyangzhen
Copy link

Fixes #987

Problem

When options.maxFiles is set and a request exceeds the limit, file handles are leaked and never released until the process exits.

Root cause in _handlePart:

  1. this.emit('fileBegin', part.name, file) — triggers the maxFiles check
  2. maxFiles check calls this._error(), destroying files in this.openedFiles
  3. But _handlePart continues and calls file.open() + this.openedFiles.push(file)
  4. This new file stream is opened after the error handling ran, so it's never closed

Fix

Check this.error after emitting fileBegin but before file.open(). If an error occurred (e.g., maxFiles exceeded), decrement _flushing and return early to prevent opening the file stream.

Reproduction

import formidable from 'formidable'

const form = formidable({
  maxFiles: 1,
  uploadDir: './uploads',
  keepExtensions: true,
})

// Upload 2 files — the 2nd file's write stream is never closed
form.parse(req)

With the fix, no file handles are leaked when maxFiles is exceeded.

Fixes node-formidable#987

When maxFiles limit is reached, the fileBegin event handler calls _error(),
but _handlePart continues and opens a write stream for the new file.
These file handles are never closed.

Fix: check this.error after emitting fileBegin and before file.open().
If an error occurred (e.g., maxFiles exceeded), decrement _flushing
and return early to prevent the file stream from being opened.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

File handle not released after options.maxFiles check

1 participant