File resources are not reliably released

File resources are not reliably released

Description

Using file resources obtained with fs.openSync() or fs.promises.open() without a reliable close() call may leave file descriptors open after normal returns or exceptions.

Potential impact

  • Leaked descriptors may accumulate across requests and cause denial of service.
  • File locks or exhausted resources may prevent legitimate requests from succeeding.

Remediation

  • Close file handles in try/finally.
  • Prefer high-level file APIs with clear resource lifetimes where possible.

Examples

These excerpts are inside a function with fs and path already available.

Before

javascript
const fd = fs.openSync(path, "r");
return fs.readFileSync(fd);

After

javascript
const fd = fs.openSync(path, "r");
try {
  return fs.readFileSync(fd);
} finally {
  fs.closeSync(fd);
}

Explanation:

  • Before: Without a reliable close operation, the descriptor may remain open after the read returns or throws.
  • After: finally closes the descriptor whether the read succeeds or throws an exception.

References