← Back to Node.js Course | Chapter 5: File System | Lesson 1 of 7

Reading files (sync/async)

You can read a file all at once, either blocking the program or without blocking it.
Syntax
javascript
const data = fs.readFileSync('path', 'utf8');

fs.readFile('path', 'utf8', (err, data) => {
  // handle err, use data
});

Reading files (sync/async)

readFileSync returns the contents immediately and blocks. fs.readFile takes a callback and fs.promises.readFile returns a promise. Both need an encoding to return text. Errors like ENOENT show that the file is missing.

Note: Use async reads in servers and sync reads in start-up scripts.

Example: Reading files (sync/async)

javascript
const fs = require("fs");
fs.writeFileSync("data.txt", "line one\nline two");
console.log(fs.readFileSync("data.txt", "utf8").split("\n"));
fs.readFile("data.txt", "utf8", (err, text) => console.log("async length:", text.length));
try { fs.readFileSync("missing.txt"); } catch (e) { console.log(e.code); }

// Output:
// [ 'line one', 'line two' ]
// ENOENT
// async length: 17

⚠️ Run this in your own terminal or Node.js environment.

Related Topics
Common Mistakes
  1. Using readFileSync in a request handler
  2. Forgetting the encoding
  3. Not catching ENOENT
Chapter Summary
  • readFileSync blocks
  • readFile uses callbacks
  • fs.promises returns promises
  • Pass utf8 for text
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.