ERR_INVALID_FD
Node.jsERRORNotableFilesystemHIGH confidence

File descriptor is not valid

Production Risk

Low — validate fds before use, especially in code that opens and closes files dynamically.

What this means

Thrown when an invalid file descriptor (fd) is passed to a filesystem or I/O operation. A valid file descriptor must be a non-negative integer. Negative values, non-integers, or values beyond the process fd limit are invalid.

Why it happens
  1. 1Passing a negative number as a file descriptor
  2. 2Using an fd that has already been closed
  3. 3fd value is undefined or NaN from an uninitialised variable
How to reproduce

Triggered when an fs operation validates its file descriptor argument.

trigger — this will error
trigger — this will error
const fs = require('fs');
fs.fstat(-1, (err) => {
  console.error(err.code); // ERR_INVALID_FD
});

expected output

RangeError [ERR_INVALID_FD]: "fd" must be a non-negative number: -1

Fix

Validate file descriptors before use

WHEN When fd comes from a variable or external source

Validate file descriptors before use
function safeFstat(fd, cb) {
  if (!Number.isInteger(fd) || fd < 0) {
    return cb(new RangeError(`Invalid fd: ${fd}`));
  }
  fs.fstat(fd, cb);
}

Why this works

Validating that fd is a non-negative integer before calling fs APIs prevents the error.

Code examples
Triggerjs
const fs = require('fs');
fs.fstat(-1, (err) => {
  console.error(err.code); // ERR_INVALID_FD
});  // this triggers ERR_INVALID_FD
Handle in try/catchjs
try {
  // operation that may throw ERR_INVALID_FD
  riskyOperation()
} catch (err) {
  if (err.code === 'ERR_INVALID_FD') {
    console.error('ERR_INVALID_FD:', err.message)
  } else {
    throw err
  }
}
Defensive pattern to avoid itjs
// Validate inputs before calling the operation
function safe_err_invalid_fd(...args) {
  // validate args here
  return performOperation(...args)
}
What not to do

Use uninitialised or potentially closed file descriptors

Invalid fds cause immediate errors; track open/closed state carefully.

Sources
Official documentation ↗

Node.js Error Codes Documentation

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All Node.js errors