🟢 Node.js Intermediate

What is the difference between readFile and createReadStream?

Why Interviewers Ask This

Mid-level Node.js roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.

Answer

fs.readFile() reads the entire file into memory as a Buffer or string before invoking the callback. For small files this is fine, but for large files (say, a 2GB log file or video), this allocates 2GB of memory at once — potentially crashing the process. fs.createReadStream() reads the file in configurable chunks (default 64KB) and emits them as "data" events, using only a small, constant amount of memory regardless of file size. Use readFile() for: small files, configuration files, templates — any file that comfortably fits in memory and needs to be processed as a whole. Use createReadStream() for: large files, serving file downloads over HTTP, CSV/JSON processing, audio/video streaming, piping data through transforms. Example: fs.createReadStream("large.mp4").pipe(res) efficiently streams a video to the HTTP response without buffering the whole file.

Pro Tip

Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a Node.js codebase.