← Back to Node.js Course | Chapter 2: Core Modules | Lesson 1 of 7

fs module

The fs module reads and writes files and folders on your computer.

In this page:

  1. fs module
Syntax
javascript
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

javascript
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
  1. Using sync methods inside request handlers
  2. Forgetting the encoding and getting a Buffer
  3. 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:

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.