Lesson 8 of 30
File System Module
27% complete
Chapters
Chapter 8
File System Module
Learn how to read, write, update, and delete files using Node.js.
Theory
The fs module provides APIs for interacting with the file system.
Common operations include:
• Reading files
• Writing files
• Appending data
• Renaming files
• Deleting files
Node.js provides both synchronous and asynchronous file system APIs.
Asynchronous operations are generally preferred in server applications because they avoid unnecessarily blocking the event loop.
Example
Node.js Example
const fs = require("fs");
fs.writeFile(
"message.txt",
"Hello Node.js!",
(error) => {
if (error) {
console.error(error);
return;
}
console.log("File created successfully");
}
);Output
A file named message.txt is created with the specified content.
Practice
Create a file using fs.writeFile and then read it using fs.readFile.
Interview Questions
1.
What is the fs module?
2.
How do you read a file in Node.js?
3.
What is the difference between synchronous and asynchronous file operations?
Quick Quiz
Which option best matches this chapter?
A.fs
B.http
C.path
D.events
Answer: fs