🟢 Node.js Intermediate

What is the difference between readFile and createReadStream?

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.