File descriptor is not valid
Production Risk
Low — validate fds before use, especially in code that opens and closes files dynamically.
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.
- 1Passing a negative number as a file descriptor
- 2Using an fd that has already been closed
- 3fd value is undefined or NaN from an uninitialised variable
Triggered when an fs operation validates its file descriptor argument.
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
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.
const fs = require('fs');
fs.fstat(-1, (err) => {
console.error(err.code); // ERR_INVALID_FD
}); // this triggers ERR_INVALID_FDtry {
// 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
}
}// Validate inputs before calling the operation
function safe_err_invalid_fd(...args) {
// validate args here
return performOperation(...args)
}✕ Use uninitialised or potentially closed file descriptors
Invalid fds cause immediate errors; track open/closed state carefully.
Node.js Error Codes Documentation
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev