File System (fs module)
# Node.js File System (fs Module)
Welcome to Chapter 5! One of the most powerful features of Node.js is its ability to interact directly with the operating system's file system. In a browser, JavaScript is strictly forbidden from touching a user's hard drive for security reasons. But on a server, reading and writing files (like logs, configuration files, or image uploads) is an everyday task.
---
1. Introduction
To work with the file system, Node.js provides a built-in Core Module named fs (File System). Because it is built-in, you don't need to install anything. You simply require('fs') and you immediately gain the power to create, read, update, and delete files (CRUD operations).
In this chapter, we'll explore both the Synchronous (blocking) and Asynchronous (non-blocking) ways to handle files.
---
2. Learning Objectives
By the end of this chapter, you will be able to:
-
Import the built-in
fsmodule.
- Differentiate between Synchronous and Asynchronous file operations.
-
Write new files to the hard drive (
fs.writeFile).
-
Read existing files (
fs.readFile).
-
Append data to existing files (
fs.appendFile).
-
Delete files from the hard drive (
fs.unlink).
---
3. Beginner-Friendly Explanations
Synchronous vs Asynchronous
Think of ordering coffee:-
Synchronous (Blocking): You place an order, and the cashier makes you wait at the register until your coffee is done. Nobody else in line can order. In Node.js,
fs.readFileSyncstops all other code from running until the file is fully read.
-
Asynchronous (Non-Blocking): You place an order, get a receipt, and step aside. The cashier takes the next person's order. When your coffee is ready, they call your name (this is a callback function). In Node.js,
fs.readFilereads the file in the background and lets the rest of your code run immediately.
Always prefer Asynchronous methods in backend development so you don't block the server from handling other users!
---
4. Syntax Explanation
Let's look at how to require the module and write a file asynchronously.
```javascript id="ch5-syntax-1" // 1. Require the built-in fs module (Notice there is no './' !) const fs = require('fs');
// 2. Syntax: fs.writeFile(path, data, callbackFunction) fs.writeFile('./message.txt', 'Hello, File System!', (err) => { if (err) { console.error("Failed to write file:", err); return; } console.log("File was created successfully!"); });
javascript id="ch5-code-1" const fs = require('fs');
// readFile requires specifying 'utf8' encoding, // otherwise it returns a raw Buffer (binary data) fs.readFile('./greeting.txt', 'utf8', (err, data) => { if (err) { console.error(err); return; } console.log("File Contents:"); console.log(data); });
javascript id="ch5-code-2" const fs = require('fs');
const newLog = "\nUser logged in at " + new Date().toLocaleTimeString();
fs.appendFile('./activity.log', newLog, (err) => { if (err) throw err; console.log("Log saved!"); });
javascript id="ch5-code-3" const fs = require('fs');
// Deletes the file named temp.txt fs.unlink('./temp.txt', (err) => { if (err) { console.error("Could not find file to delete."); return; } console.log("File deleted successfully!"); });
javascript id="ch5-code-4" const fs = require('fs');
fs.mkdir('./my-new-folder', (err) => { if (err) throw err; console.log("Folder created!"); });
javascript const fs = require('fs/promises');
async function readMyFile() { const data = await fs.readFile('./data.txt', 'utf8'); console.log(data); }
javascript id="ch5-mini-project" // notes.js const fs = require('fs');
const command = process.argv[2]; const content = process.argv[3]; const filePath = './mynotes.txt';
if (command === 'add') {
if (!content) {
console.log("Please provide a note to add. (Wrap in quotes)");
process.exit(1);
}
const formattedNote = - ${content}\n;
fs.appendFile(filePath, formattedNote, (err) => {
if (err) throw err;
console.log("✅ Note added successfully!");
});
} else if (command === 'read') { fs.readFile(filePath, 'utf8', (err, data) => { if (err) { console.log("No notes found or error reading file."); return; } console.log("\n--- My Notes ---"); console.log(data); console.log("----------------\n"); });
} else {
console.log("Command not recognized. Use 'add' or 'read'.");
}
``
Run it:
node notes.js add "Learn Node.js FS module"
node notes.js add "Buy groceries"
node notes.js read
---
12. Coding Challenges
Challenge 1: Add a delete command to the notes app that uses fs.unlink to completely delete the mynotes.txt file.
Challenge 2: Write a script that checks if a file exists before trying to read it. (Hint: look up fs.existsSync() in the Node.js documentation).
---
13. MCQs with Answers
Q1: Which core module is used to interact with the file system?
A) file
B) os
C) fs
D) path
Answer: C
Q2: If you use fs.readFile without specifying an encoding like 'utf8', what does it return?
A) A String
B) An Error
C) A Buffer
D) A Boolean
Answer: C
Q3: Which method is non-blocking (asynchronous)?
A) fs.writeFileSync()
B) fs.writeFile()
C) fs.readFileSync()
D) fs.appendFileSync()
Answer: B
Q4: Which function is used to delete a file?
A) fs.delete()
B) fs.remove()
C) fs.trash()
D) fs.unlink()
Answer: D
---
14. Interview Questions
- 1. What is the difference between Synchronous and Asynchronous file operations in Node.js?
- 2. What is a Buffer in Node.js?
- 3. How do you require a core module vs a local module?
), while local custom modules must include a relative path (require('./myFile')).
---
15. FAQs
Q: Can
fs write HTML files or JSON files?
A: Yes! A file is just data. You can write fs.writeFile('index.html', '<h1>Hello</h1>', ...) and it will perfectly create an HTML file.
Q: Where does Node.js save the file if I don't give a full path?
A: If you just say
./file.txt, it saves it in the current working directory—the folder from which you ran the node command in your terminal.
---
16. Summary
-
The
fs module is built into Node.js and handles file operations.
-
Always use Asynchronous methods (
writeFile, readFile) in production to avoid blocking the event loop.
-
Use
'utf8' encoding when reading files to get readable text instead of Buffers.
-
Use
fs.appendFile to add text without overwriting, and fs.unlink to delete files.
---
17. Next Chapter Recommendation
When dealing with files, file paths can get very messy depending on whether you are using Windows (
C:\folder\file) or Mac/Linux (/folder/file`). In Chapter 6: Node.js Path Module, we will learn how to handle file paths dynamically and safely across all operating systems!