skip to content

In Node's fs/promises API, why must every FileHandle be closed explicitly, and what happens in Node 24 when one is left for garbage collection?

level: middleimportance: should knowfreq 35%

answer

  1. a wrapper around a numeric descriptor
  2. descriptors are a finite table
  3. a warning now, an error next
  4. Symbol.asyncDispose and await using

basics

~20 s

A FileHandle owns an operating-system file descriptor, and descriptors run out. Node 24 tries to close a forgotten handle on garbage collection, with a warning and no guarantee; from v25.0.0 it throws. Close it in finally, or use await using.

solid answer

~40 s

`fsPromises.open()` returns a `FileHandle`, an object wrapping a numeric file descriptor. The process has a limited number of descriptors, so leaked handles end in `EMFILE` on later opens. In Node 24, if a handle is garbage-collected while open, Node tries to close the descriptor and emits a process warning, deprecation `DEP0137`, but the docs say not to rely on it: garbage collection may come late or not at all. From v25.0.0 that path is End-of-Life and throws, so on Node 26 LTS a leaked handle raises an error instead of a warning. Close with `await fh.close()` in `finally`, or write `await using fh = await open(path)`, which calls `filehandle[Symbol.asyncDispose]()` when the block exits, stable since v24.2.0. When you do not need the handle, `readFile(path)` manages one for you.

code

javascript · 19 lines
javascript
import { open } from 'node:fs/promises';

// Works on every supported release
async function firstBytes(path) {
  let fh;
  try {
    fh = await open(path, 'r');
    const { bytesRead, buffer } = await fh.read({ buffer: Buffer.alloc(16), position: 0 });
    return buffer.subarray(0, bytesRead);
  } finally {
    await fh?.close();
  }
}

// Node 24: closed automatically when the block exits, even on throw
async function size(path) {
  await using fh = await open(path, 'r');
  return (await fh.stat()).size;
}

go deeper

for a junior

Recall that fsPromises.open returns a FileHandle you must close, and that the try/finally pattern does it even when a read throws.

for a middle

Explain what a descriptor is, why leaks end in EMFILE, how await using calls Symbol.asyncDispose, and that Node 24 only warns where Node 25 and later throw.

for a senior

Treat DEP0137 warnings in production logs as defects before an upgrade, and recognise a handle leak behind intermittent EMFILE errors on unrelated opens.

for a principal

Plan the Node 26 LTS upgrade around it: make lingering handle leaks visible on 24 so moving to the next LTS does not turn warnings into crashes.

## What a FileHandle is A **file descriptor** is the small integer the operating system hands a process when it opens a file; every later read, write or stat on that open file names it. The kernel keeps a per-process table of them and **limits its size**. In Node's promise API, `fsPromises.open(path, flags)` returns a **`FileHandle`**: an object that wraps that numeric descriptor (available as `fh.fd`) and exposes methods such as `read`, `write`, `stat`, `readFile`, `createReadStream` and `close`. A `FileHandle` is also an `EventEmitter` that emits `'close'` once it can no longer be used. The higher-level helpers `readFile(path)`, `writeFile(path, data)` and `appendFile(path, data)` open and close a handle internally. You only own a handle, and its closing, when you call `open()` yourself, typically to do several operations on one open file or to read part of it. ## Why closing is your job - **Descriptors are finite.** The fs documentation says failing to close them results in a leak that will eventually crash the application. In practice the first symptom is an `EMFILE` error ("too many open files") on unrelated `open` calls. - **The GC safety net is weak.** In Node 24, a `FileHandle` that is garbage-collected while still open makes Node try to close the descriptor and emit a process warning. The docs call this unreliable: the file **may not be closed**, and nothing forces garbage collection to run soon on a process with free memory. - **The net is being removed.** Closing a `FileHandle` on garbage collection has been a runtime deprecation, `DEP0137`, since v14.0.0. In v25.0.0 it became End-of-Life: the same leak now **throws an error** instead of warning. Node 26, the next LTS line, carries that change, so a leak that only logs a warning on Node 24 becomes a crash after the upgrade. - **Close waits for pending work.** `filehandle.close()` waits for any operation in progress on that handle to complete before it closes. ## Two ways to close correctly 1. **`try`/`finally`.** Declare the variable outside, assign inside, close in `finally` with optional chaining so a failed `open()` does not throw again. 2. **`await using`.** Node 24 ships V8 13.6, which brings explicit resource management to JavaScript. `FileHandle` implements `[Symbol.asyncDispose]()`, which calls `close()`. With `await using fh = await open(p)` the handle is closed when the enclosing block exits, on the normal path and when it throws. The method was added in v20.4.0 and v18.18.0 and marked stable in v24.2.0. | Pattern | Closes on throw | Needs Node 24 | Note | |---|---|---|---| | `try { } finally { await fh?.close(); }` | yes | no | works on every supported release | | `await using fh = await open(p)` | yes | yes | scope-based, the shortest form | | relying on garbage collection | not reliably | not applicable | warns in 24, throws from 25 | ## Related habits - **Streams from a handle** close it for you by default: `fh.createReadStream()` has `autoClose: true`, which closes the descriptor on `'error'` or `'end'`. Set `autoClose: false` and closing is yours again. Stream mechanics themselves belong to the streams material. - **Directories are resources too.** `fsPromises.opendir()` returns an `fs.Dir`; iterating it with `for await` closes it automatically, and in Node 24 it also supports `await using`. - **Do not share a handle across concurrent writes.** The docs warn that calling `filehandle.write()` or `filehandle.writeFile()` several times on the same file without waiting is unsafe. - **Finding leaks.** Watch the process warnings in logs: on Node 24, every garbage-collected handle is a leak you can still fix before the warning becomes an error. ## Diagnosing a handle leak in production 1. **Recognise the symptom.** `EMFILE` on opens, sockets or child processes that have nothing to do with the leaking code, often only after hours of uptime. 2. **Look for the warnings.** On Node 24 the leak usually shows up as process warnings, including the `DEP0137` deprecation, because some handles do get collected. 3. **Make it fail early.** Running the test suite with `--throw-deprecation` turns deprecation warnings into thrown errors, which approximates the behaviour of the next release line. 4. **Audit every `open()`.** Each one needs a matching `close()` on every path, including early `return`s and thrown errors; converting them to `await using` makes the guarantee structural rather than a matter of discipline.

  • A Node service upgraded from 24 to a newer release now crashes intermittently with an error about a FileHandle closed during garbage collection. What happened?
    Code somewhere opens a `FileHandle` and never closes it. On Node 24 the garbage collector closed it with a deprecation warning, `DEP0137`, that nobody read. From v25.0.0 that path is End-of-Life and throws instead. Find the `open()` without a matching `close()` and add `try/finally` or `await using`.
  • Do you need to call fh.close() after await readFile(path) from node:fs/promises?
    No. When `readFile` receives a path it opens and closes its own handle. You only close what you opened. If you pass an existing `FileHandle` to `readFile`, the handle stays open and closing it remains your job.

A FileHandle is like a library book on loan: the library has a fixed number of copies, and a book nobody returns may eventually be collected by a cleaner, but the library is moving to fining you for that instead.

  • Garbage collection closes a leaked FileHandle, so explicit close() is optional
  • Leaking a FileHandle on Node 24 is harmless because only a warning appears
  • await using needs an experimental flag in Node 24
  • readFile(path) returns a handle the caller must close afterwards
  • Closing a FileHandle flushes its data to disk like filehandle.sync()

Assumes Node 24: a FileHandle closed by garbage collection only warns (DEP0137); from v25.0.0, and so in Node 26 LTS, it throws.