File System - File Operations Basics
🏠 The Magic Filing Cabinet
Imagine your computer is like a giant house with rooms full of filing cabinets. Each filing cabinet holds folders, and each folder holds papers with information on them. Node.js gives you a special magic key called the fs module that lets you:
- Read papers (files) to see what’s written on them
- Write new papers with your own words
- Add more words to papers that already exist
- Organize everything neatly
Let’s explore this magic filing cabinet together!
📦 The fs Module Overview
The fs module is your toolbox for working with files. Think of it like a librarian who can:
- Find any book (file) you ask for
- Write new books for you
- Add pages to existing books
- Tell you about books without opening them
How to Get the Toolbox
// Old way (still works great!)
const fs = require('fs');
// New way (modern and cool)
import fs from 'fs';
The fs module comes free with Node.js - no extra installation needed!
Two Flavors of fs
| Flavor | How It Works | Best For |
|---|---|---|
| Callbacks | “Call me when done!” | Quick scripts |
| Promises | “I promise to finish!” | Modern apps |
📖 Reading Files
Reading a file is like opening a book and looking at what’s inside.
The Story
Little Timmy wanted to read his favorite storybook. He asked the librarian (fs module), “Please read
story.txtto me!” The librarian opened the book and read it out loud.
Synchronous Reading (Wait Until Done)
const fs = require('fs');
// Read the whole file at once
const content = fs.readFileSync(
'story.txt',
'utf8'
);
console.log(content);
// Shows: "Once upon a time..."
What happens: Your program stops and waits until the file is completely read.
Asynchronous Reading (Don’t Wait!)
const fs = require('fs');
fs.readFile('story.txt', 'utf8',
(error, content) => {
if (error) {
console.log('Oops!', error);
return;
}
console.log(content);
}
);
console.log('I run first!');
What happens: Your program keeps running while the file is being read.
graph TD A[Start Reading] --> B{Sync or Async?} B -->|Sync| C[Wait for file] C --> D[Get content] B -->|Async| E[Keep running code] E --> F[Callback runs later] F --> D
✍️ Writing Files
Writing a file is like getting a blank paper and writing your message on it.
The Story
Sarah had an important message to save. She gave the librarian a blank paper and said, “Please write ‘I love coding!’ on this and save it as
message.txt.” The librarian wrote it down carefully.
Synchronous Writing
const fs = require('fs');
fs.writeFileSync(
'message.txt',
'I love coding!'
);
console.log('Saved!');
Asynchronous Writing
const fs = require('fs');
fs.writeFile(
'message.txt',
'I love coding!',
(error) => {
if (error) {
console.log('Oops!', error);
return;
}
console.log('Saved!');
}
);
⚠️ Warning:
writeFilereplaces everything! Ifmessage.txtalready had words, they’re gone now!
➕ Appending to Files
Appending is like adding more pages to a book without erasing what’s already there.
The Story
Every day, Jake writes what he learned in his diary. He doesn’t want to erase yesterday’s entry - he wants to add to it! So he uses
appendFileto write at the end.
Synchronous Appending
const fs = require('fs');
fs.appendFileSync(
'diary.txt',
'\nDay 2: Learned about fs!'
);
Asynchronous Appending
const fs = require('fs');
fs.appendFile(
'diary.txt',
'\nDay 2: Learned about fs!',
(error) => {
if (error) {
console.log('Oops!', error);
return;
}
console.log('Entry added!');
}
);
| Method | What It Does |
|---|---|
writeFile |
Erases old content, writes new |
appendFile |
Keeps old content, adds new at end |
🌟 The fs/promises API
The promises version of fs is like having a super-smart assistant who says “I promise I’ll do this, and I’ll tell you when I’m done!”
Why Promises Are Awesome
- No “callback pyramids” (nested callbacks)
- Use
async/awaitfor clean code - Easier error handling with
try/catch
Getting the Promise Toolbox
// The modern way!
const fs = require('fs/promises');
// Or with import
import fs from 'fs/promises';
Reading with Promises
const fs = require('fs/promises');
async function readMyFile() {
try {
const content = await fs.readFile(
'story.txt',
'utf8'
);
console.log(content);
} catch (error) {
console.log('Oops!', error);
}
}
readMyFile();
Writing with Promises
const fs = require('fs/promises');
async function saveMessage() {
try {
await fs.writeFile(
'note.txt',
'Hello from promises!'
);
console.log('Saved!');
} catch (error) {
console.log('Oops!', error);
}
}
saveMessage();
graph TD A[fs.promises Method] --> B[Returns Promise] B --> C[Use await] C --> D{Success?} D -->|Yes| E[Continue Code] D -->|No| F[Catch Error]
📋 Working with JSON Files
JSON files are like organized lists that both humans and computers can understand.
The Story
Emma has a list of her favorite toys. Instead of writing “teddy bear, robot, puzzle” on paper, she uses JSON to keep it organized so her computer friend can understand it too!
What JSON Looks Like
{
"name": "Emma",
"age": 8,
"toys": ["teddy", "robot"]
}
Reading JSON Files
const fs = require('fs');
// Step 1: Read the file (it's just text)
const data = fs.readFileSync(
'toys.json',
'utf8'
);
// Step 2: Convert text to JavaScript
const toys = JSON.parse(data);
console.log(toys.name); // "Emma"
console.log(toys.toys); // ["teddy", "robot"]
Writing JSON Files
const fs = require('fs');
const myData = {
name: 'Jake',
score: 100,
level: 5
};
// Convert JavaScript to text (pretty!)
const jsonText = JSON.stringify(
myData,
null,
2
);
fs.writeFileSync('game.json', jsonText);
The Two Magic Spells
| Spell | What It Does |
|---|---|
JSON.parse() |
Text → JavaScript object |
JSON.stringify() |
JavaScript object → Text |
🚨 Error-First Callback Pattern
This is Node.js’s special way of saying “If something goes wrong, I’ll tell you first!”
The Story
When you ask the librarian for a book, they might say:
- “Sorry, I couldn’t find it” (error first!)
- “Here’s your book!” (success second)
The Pattern
fs.readFile('book.txt', 'utf8',
(error, data) => {
// ALWAYS check error FIRST!
if (error) {
console.log('Problem:', error.message);
return; // Stop here!
}
// Only use data if no error
console.log('Content:', data);
}
);
Why Error First?
- Forces you to handle problems - Can’t ignore errors
- Consistent pattern - All Node.js callbacks work this way
- Safe code - Prevents crashes from missing files
graph TD A[Callback Runs] --> B{error exists?} B -->|Yes| C[Handle Error] C --> D[Stop/Return] B -->|No| E[Use Data Safely] E --> F[Continue Program]
Common Errors to Handle
| Error Code | What It Means |
|---|---|
ENOENT |
File not found |
EACCES |
No permission |
EISDIR |
It’s a folder, not a file |
Example: Safe File Reading
const fs = require('fs');
fs.readFile('config.json', 'utf8',
(error, data) => {
if (error) {
if (error.code === 'ENOENT') {
console.log('File missing!');
} else {
console.log('Error:', error);
}
return;
}
const config = JSON.parse(data);
console.log('Config loaded!');
}
);
🎯 Quick Reference
| Task | Method |
|---|---|
| Read file | fs.readFile() / fs.readFileSync() |
| Write file | fs.writeFile() / fs.writeFileSync() |
| Add to file | fs.appendFile() / fs.appendFileSync() |
| Promise read | fs.promises.readFile() |
| Promise write | fs.promises.writeFile() |
🌈 You Did It!
You now know how to:
- ✅ Use the
fsmodule - ✅ Read files (sync and async)
- ✅ Write new files
- ✅ Append to existing files
- ✅ Use the modern
fs/promisesAPI - ✅ Work with JSON files
- ✅ Handle errors the Node.js way
You’re now a File System wizard! 🧙♂️✨