Lab 09: Node.js File System

🎯 Objective

Read, write, copy, and process files using Node.js fs module, both synchronous and asynchronous APIs, plus path and stream for large files.

⏱️ Estimated Time

30 minutes

📋 Prerequisites

  • Lab 8: Modules

🛠️ Tools Used

  • Node.js 20 (fs, path, stream built-ins)

🔬 Lab Instructions

Step 1: Writing and Reading Files

const fs = require("fs");
const path = require("path");

const FILE = "/tmp/demo.txt";

// Write synchronously
fs.writeFileSync(FILE, "Line 1\nLine 2\nLine 3\n");
console.log("Written:", fs.statSync(FILE).size, "bytes");

// Read entire file
const content = fs.readFileSync(FILE, "utf8");
console.log("Content:\n" + content.trim());

// Read line by line using split
const lines = content.trim().split("\n");
lines.forEach((line, i) => console.log(`  [${i}] ${line}`));

📸 Verified Output:

Step 2: Async File Operations

📸 Verified Output:

Step 3: Working with Directories

📸 Verified Output:

Step 4: JSON Config Files

📸 Verified Output:

Step 5: Streams for Large Files

📸 Verified Output:

Step 6: Path Module

📸 Verified Output:

Step 7: File Watching

📸 Verified Output:

Step 8: CSV File Processing

📸 Verified Output:

✅ Verification

Expected output:

🚨 Common Mistakes

  1. Sync in async context: fs.readFileSync() in a server handler blocks the event loop — use fs.promises.

  2. Not checking if file exists: readFileSync on missing file throws — check fs.existsSync() first or use try/catch.

  3. Relative paths: readFileSync("./file.txt") — relative to process.cwd(), not __dirname. Use path.join(__dirname, "file.txt").

  4. Missing utf8 encoding: readFileSync(path) returns a Buffer; add "utf8" for string.

  5. Not closing streams: Unclosed write streams may not flush — always call .end() and wait for "finish".

📝 Summary

  • fs.readFileSync/writeFileSync — synchronous, blocks event loop (OK for startup)

  • fs.promises.readFile/writeFile — async, non-blocking (use in request handlers)

  • readline + createReadStream — memory-efficient line-by-line reading for large files

  • path.join/resolve/parse — cross-platform path handling

  • fs.watch — file change notifications

🔗 Further Reading

Last updated