QA
Intermediate LevelNode JS

What is a file descriptor (FD) leak and how do you ensure files are closed using fs.close() or file handles?

❓ Interview Prompt: Opening files with fs.open() consumes OS file descriptors (ulimit -n limit ~1024). Forgetting fs.close(fd) causes EMFILE: too many open files crashes. Always use Promise file handles: const fd = await fs.open(...); try { ... } finally { await fd.close(); }.

In Linux/macOS, opening a file consumes a numeric File Descriptor (FD). Operating systems cap max open FDs per process ('ulimit -n', default 1024):

File Descriptor Leak:

Opening files without calling 'close()' exhausts open FDs, triggering 'EMFILE: too many open files' crashes!

•
Always use 'try / finally' blocks with Promise file handles to guarantee file closure.

Code Implementation Example

javascript
import fs from 'node:fs/promises';

async function safeFileRead(filename) {
  let fileHandle;
  try {
    fileHandle = await fs.open(filename, 'r');
    const content = await fileHandle.readFile('utf8');
    return content;
  } finally {
    if (fileHandle) await fileHandle.close(); // Guarantees FD is released!
  }
}
💡Safely releasing file handles using try/finally blocks to prevent FD leaks.
🎯 Interview Key Takeaway

Always close file handles in a finally block to prevent File Descriptor leaks and EMFILE crashes.

#File Descriptors#FD Leak#fs.open#EMFILE#Intermediate
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?