Course contentsShow
← JavaScript
Lesson 1518 of 2,72333. JavaScript in Node.jsFree lesson

Reading Files with fs.readFile()

Reading entire file contents asynchronously into memory with callbacks or promises.

Reading Files with fs.readFile()

You'll learn how to read entire file contents into memory asynchronously using Node.js's callback-based file reading method.

What is fs.readFile()?

fs.readFile() is Node.js's primary asynchronous method for loading a complete file from disk into memory. Think of it like asking a librarian to fetch you a book — you don't stand there waiting; you continue doing other things, and the librarian calls you back when the book is ready.

Basic Callback Syntax

The classic approach uses a callback function that receives an error (if something went wrong) or the file data:

const fs = require('fs');

fs.readFile('example.txt', 'utf8', (err, data) => {
  if (err) {
    console.error('Error reading file:', err);
    return;
  }
  console.log('File contents:', data);
});

console.log('This runs while the file is being read!');

The second argument 'utf8' tells Node.js to decode the file as text. Without it, you'd get raw binary data as a Buffer.

How It Works

Unlike synchronous file operations that block your entire program, fs.readFile() hands the work to the operating system and lets your code continue running. When the file is loaded, your callback fires with the results. This keeps your Node.js application responsive, especially important when handling multiple requests.

Error-First Callback Pattern

Notice the err parameter comes first — this is Node.js convention. Always check for errors before using data, because if reading failed, data will be undefined.

Key Takeaway: fs.readFile() loads entire files asynchronously using callbacks, following the error-first pattern to prevent blocking your program while I/O operations complete.