The Node.js File System module allows us to create, read, update, rename, and delete files and directories. It is commonly used in applications that need to store or retrieve information from files.
fs module helps
Node.js programs work with files and folders on a computer.
Node.js provides a built-in module called fs.
We can use it without installing an additional package.
Some common file operations are:
const fs = require('node:fs');
console.log("File System Module Loaded");
Output:
File System Module Loaded
The require('node:fs') statement loads the
built-in File System module using CommonJS.
import fs from 'node:fs';
console.log("File System Module Loaded");
Use this import syntax when your project is configured to use ES Modules.
The writeFileSync() method writes data to a file
synchronously. If the file does not exist, Node.js creates it.
If it already exists, its contents are replaced by default.
const fs = require('node:fs');
fs.writeFileSync('student.txt', 'Welcome to Node.js');
console.log("File created successfully");
Output:
File created successfully
A file named student.txt is created in the
current working directory if it does not already exist.
The readFileSync() method reads file contents
synchronously. Providing 'utf8' returns text
instead of a Buffer.
Suppose student.txt contains:
Welcome to Node.js
Create app.js:
const fs = require('node:fs');
const data = fs.readFileSync('student.txt', 'utf8');
console.log(data);
Output:
Welcome to Node.js
The appendFileSync() method adds data to the end
of a file. If the file does not exist, it creates the file.
const fs = require('node:fs');
fs.appendFileSync('student.txt', '\nLearning File System Module');
console.log("Data appended successfully");
Updated file contents:
Welcome to Node.js
Learning File System Module
The newline character \n moves the appended
text to a new line.
You can use writeFileSync() to replace the contents
of an existing file with new text.
const fs = require('node:fs');
fs.writeFileSync('student.txt', 'Node.js File Updated');
console.log("File updated successfully");
New file contents:
Node.js File Updated
writeFileSync() replaces the existing
contents by default. Use appendFileSync()
when you want to add text without replacing existing data.
The renameSync() method renames a file or moves it
to another location.
const fs = require('node:fs');
fs.renameSync('student.txt', 'student_data.txt');
console.log("File renamed successfully");
Result:
student.txt → student_data.txt
Run this example after creating student.txt.
If the source file does not exist, the operation will fail.
The unlinkSync() method deletes a file.
const fs = require('node:fs');
fs.unlinkSync('student_data.txt');
console.log("File deleted successfully");
Output:
File deleted successfully
The existsSync() method checks whether a path exists.
It returns true or false.
const fs = require('node:fs');
if (fs.existsSync('student.txt')) {
console.log("File exists");
} else {
console.log("File does not exist");
}
The output depends on whether
student.txt exists in the current working
directory.
In applications that need to handle possible file errors, it is often better to attempt the required operation and handle its error rather than rely on an existence check before acting.
The mkdirSync() method creates a directory.
Use the recursive option when parent directories
may also need to be created.
const fs = require('node:fs');
fs.mkdirSync('students', { recursive: true });
console.log("Folder created successfully");
Output:
Folder created successfully
The readdirSync() method returns the names of
files and directories inside a directory.
const fs = require('node:fs');
const files = fs.readdirSync('.');
console.log(files);
The dot (.) represents the current working
directory. The output is an array of entry names, and
it depends on the contents of that directory.
The File System module offers synchronous and asynchronous methods. Synchronous methods block execution until the operation finishes. Asynchronous methods allow other JavaScript work to continue while the operation is pending.
| Operation | Synchronous Method | Asynchronous Method |
|---|---|---|
| Read a file | readFileSync() |
readFile() |
| Write a file | writeFileSync() |
writeFile() |
| Append data | appendFileSync() |
appendFile() |
| Rename a file | renameSync() |
rename() |
| Delete a file | unlinkSync() |
unlink() |
The asynchronous readFile() method uses a callback
to receive the file contents or an error.
const fs = require('node:fs');
fs.readFile('student.txt', 'utf8', function(err, data) {
if (err) {
console.error("Unable to read file:", err.message);
return;
}
console.log(data);
});
console.log("Reading file...");
The message Reading file... can appear before
the file contents because the read operation is
asynchronous.
fs module.mydata.txt containing Hello Students.Welcome to Node.js to the file.myfolder.Hint:
const fs = require('node:fs');
fs.writeFileSync('mydata.txt', 'Hello Students');
console.log(fs.readFileSync('mydata.txt', 'utf8'));
fs.appendFileSync('mydata.txt', '\nWelcome to Node.js');
console.log(fs.readFileSync('mydata.txt', 'utf8'));
fs.mkdirSync('myfolder', { recursive: true });
console.log(fs.readdirSync('.'));
Select the correct answer for each question.
1. Which method reads a file synchronously?
2. Which method adds data to the end of a file?
3. Which method deletes a file?