FS Module: Managing Files

FS Module: Managing Files in JavaScript: Imagine your computer is a massive library. The FS (File System) Module is the Librarian.

Concept Explanation

Imagine your computer is a massive library. The FS (File System) Module is the Librarian. You can ask it to find a book (read a file), write a new book (create a file), or even burn a book (delete a file).


Syntax or Core Structure

Reading a File (The Modern Way)

import { readFile } from 'node:fs/promises';

try {
  const content = await readFile('./data.txt', 'utf-8');
  console.log(content);
} catch (err) {
  console.error("Could not read file!");
}

Writing a File

import { writeFile } from 'node:fs/promises';

await writeFile('./hello.txt', 'Hello from Node.js!');

Common Mistakes

  1. Wrong Paths: Node looks for files relative to where you run the script, not where the file is. Always use path.join() to build safe paths.
  2. Missing Encoding: If you forget 'utf-8', Node will return a Buffer (raw computer data) instead of human-readable text.
  3. Blocking with Sync: Avoid readFileSync in servers. If the file is 1GB, the server will stop working for everyone until it's finished reading.

Practice Exercises

  1. The File Creator: Write a script that asks the user for a "Secret Message" via the terminal and saves it to a file called secret.txt.
  2. The Folder Scanner: Use readdir to list every file in your current directory.
  3. The Cleaner: Create a file, wait 3 seconds, and then delete it using unlink.