fs module
The fs module reads and writes files and folders on your computer.
In this page:
Syntax
const fs = require('fs');
const data = fs.readFileSync('path', 'utf8');
fs.readFile('path', 'utf8', (err, data) => {
// handle err, use data
});
fs module
fs offers synchronous, callback and promise APIs. The sync versions such as readFileSync block, which is fine for scripts, while the async ones suit servers. Use utf8 as the encoding to get strings instead of Buffers.
Note:
In servers prefer fs.promises or callbacks to avoid blocking the event loop.
Example: fs module
const fs = require("fs");
fs.writeFileSync("note.txt", "hello fs");
console.log(fs.readFileSync("note.txt", "utf8"));
console.log("exists:", fs.existsSync("note.txt"));
console.log("size:", fs.statSync("note.txt").size);
// Output:
// hello fs
// exists: true
// size: 8
⚠️ Run this in your own terminal or Node.js environment.
Related Topics
Common Mistakes
- Using sync methods inside request handlers
- Forgetting the encoding and getting a Buffer
- Not handling errors like ENOENT
Chapter Summary
- fs reads and writes files
- Sync, callback and promise variants
- Pass utf8 for text
- Handle errors such as ENOENT
🔒
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: