Node.js provides file system methods that allow us to read data from files and write new data into files. These operations are useful for storing information, reading configuration files, generating reports, and managing application data.
The built-in fs module provides methods for reading
and writing files. We do not need to install an extra package.
const fs = require('node:fs');
console.log("File System Module Ready");
Output:
File System Module Ready
This example uses CommonJS syntax. If your project uses
ES Modules, you can write
import fs from 'node:fs'; instead.
The writeFileSync() method writes data to a file.
It creates the file if it does not exist and replaces existing
contents by default.
Create a file named write.js:
const fs = require('node:fs');
fs.writeFileSync('message.txt', 'Hello Students');
console.log("Data written successfully");
Output:
Data written successfully
A file named message.txt will contain:
Hello Students
The readFileSync() method reads a file
synchronously. Passing 'utf8' tells Node.js to
return the file contents as a string.
const fs = require('node:fs');
const data = fs.readFileSync('message.txt', 'utf8');
console.log(data);
Output:
Hello Students
We can use the newline character \n to write
multiple lines into a file.
const fs = require('node:fs');
const content = "Name: Amit\nCourse: Node.js\nCity: Gaya";
fs.writeFileSync('student.txt', content);
console.log("Student information saved");
Contents of student.txt:
Name: Amit
Course: Node.js
City: Gaya
The appendFileSync() method adds new data to the
end of a file instead of replacing its existing contents.
Suppose message.txt contains:
Hello Students
Now run:
const fs = require('node:fs');
fs.appendFileSync('message.txt', '\nWelcome to Node.js');
console.log("New data added");
Updated file contents:
Hello Students
Welcome to Node.js
The asynchronous writeFile() method allows Node.js
to continue doing other work while the file operation is pending.
Its callback receives an error if the operation fails.
const fs = require('node:fs');
fs.writeFile('async.txt', 'Hello from asynchronous Node.js', function(err) {
if (err) {
console.error("Error writing file:", err.message);
return;
}
console.log("File written successfully");
});
console.log("Write operation started");
The message Write operation started may
appear before the success message because the file
operation is asynchronous.
The asynchronous readFile() method reads a file
and passes its contents to a callback when the operation finishes.
const fs = require('node:fs');
fs.readFile('async.txt', 'utf8', function(err, data) {
if (err) {
console.error("Error reading file:", err.message);
return;
}
console.log("File contents:", data);
});
console.log("Reading started");
Possible output order:
Reading started
File contents: Hello from asynchronous Node.js
The file must exist before it can be read successfully. Run the previous writing example first.
Node.js provides node:fs/promises, which offers
promise-based file operations. These work well with
async and await.
const fs = require('node:fs/promises');
async function readStudentFile() {
try {
const data = await fs.readFile('student.txt', 'utf8');
console.log(data);
} catch (err) {
console.error("Unable to read file:", err.message);
}
}
readStudentFile();
The await keyword waits for the file-reading
promise to settle inside the asynchronous function.
The try...catch block handles errors.
| Method | Purpose | Behavior |
|---|---|---|
writeFileSync() |
Write or replace file contents | Synchronous |
readFileSync() |
Read file contents | Synchronous |
appendFileSync() |
Add data to a file | Synchronous |
writeFile() |
Write file contents | Asynchronous callback |
readFile() |
Read file contents | Asynchronous callback |
fs/promises |
Promise-based file operations | Works with async/await |
students.txt with the text Student 1: Amit.Student 2: Rahul on a new line.File operation completed to another file.try...catch.Hint:
const fs = require('node:fs');
fs.writeFileSync('students.txt', 'Student 1: Amit');
fs.appendFileSync('students.txt', '\nStudent 2: Rahul');
const data = fs.readFileSync('students.txt', 'utf8');
console.log(data);
Expected output:
Student 1: Amit
Student 2: Rahul
Select the correct answer for each question.
1. Which method reads a file synchronously?
2. Which method adds new content to the end of a file?
3. Which module provides promise-based file operations?