13 / 16

Explain what the `fs.readdir()` method is used for in Node.js.

Difficulty: 3/10
directory listing, asynchronous I/O, error handling

The fs.readdir() method is used to read the contents of a directory. It returns an array of file and directory names present in the specified directory.

javascript

Scenario Questions

0-2 years experience

  1. 1How would you use fs.readdir to get a list of all files in a given folder and then log each filename?
  2. 2What will happen if you call fs.readdir on a path that doesn't exist? How would you handle that in code?

2-5 years experience

  1. 1You need to implement an endpoint that returns the names of all JSON files in a user‑provided directory, but you must ignore sub‑directories and handle large directories efficiently. Walk me through how you'd use fs.readdir and any additional steps.
  2. 2During a code review you notice that a teammate used the synchronous version of readdir in a request handler, causing latency spikes. Explain why that is a problem and how you would refactor it.

5-8 years experience

  1. 1Our service periodically scans a shared network drive containing millions of files to build an index. Discuss the trade‑offs of using fs.readdir versus streaming approaches or external tools, and how you would design the scanning component to be resilient and performant.
  2. 2When reading a directory with many entries, you sometimes get EMFILE errors. Explain why this occurs with fs.readdir and how you would mitigate it at the system design level.

8+ years experience

  1. 1We are migrating a legacy monolith that uses many nested fs.readdir calls into a microservice architecture. What architectural changes would you propose to reduce I/O pressure, improve observability, and ensure backward compatibility across teams?
  2. 2Design a cross‑team library that abstracts directory enumeration, supports both callback and promise APIs, handles permission errors uniformly, and can be swapped out for a cloud storage listing implementation in the future. What considerations would guide your design decisions?

Follow-up Questions

  • What edge cases would you test for when using fs.readdir?
  • How would you handle permission errors in production code?
  • Can you show a short snippet that uses the promise API?
Share

Share via WhatsApp, X, Facebook, LinkedIn or copy link. Open Graph preview enabled.