Reading files (sync/async)
You can read a file all at once, either blocking the program or without blocking it.
In this page:
Syntax
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)
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
- Using readFileSync in a request handler
- Forgetting the encoding
- 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: