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

When you open the file yourself, close it in finally. Use fs.closeSync(fd) for the descriptor returned by fs.openSync() and await handle.close() for the FileHandle returned by fs.promises.open(). If you do not need to manage a handle, use a high-level file API that takes a path.

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);
}

fs.readFileSync(fd) leaves the caller’s descriptor open. The revised finally closes it whether the function returns the data or the read throws.

References