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
- 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. - Missing Encoding: If you forget
'utf-8', Node will return a Buffer (raw computer data) instead of human-readable text. - Blocking with Sync: Avoid
readFileSyncin servers. If the file is 1GB, the server will stop working for everyone until it's finished reading.
Practice Exercises
- 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. - The Folder Scanner: Use
readdirto list every file in your current directory. - The Cleaner: Create a file, wait 3 seconds, and then delete it using
unlink.