Reading Files in Node.js
Reading files is one of the most common operations in Node.js. The File System module provides methods that allow us to read information stored in text files, JSON files, and other supported file formats.
In this lesson, we will learn how to read files using
fs.readFile() and fs.readFileSync(),
understand UTF-8 encoding, handle errors, and display file content
in the terminal.
1. What Does Reading a File Mean?
Reading a file means retrieving the information already stored inside a file. A Node.js application can read a file and use its content for further processing.
For example, suppose a file named student.txt
contains student information. We can read that file and display
the information in the terminal.
Name: Rahul
Course: Node.js
Reads the file using the fs module
Name: Rahul
Course: Node.js
2. The fs.readFile() Method
The fs.readFile() method reads a file
asynchronously. This means Node.js can continue executing
other JavaScript code while the file operation is being handled.
Syntax:
fs.readFile(path, encoding, callback);
Parameters:
| Parameter | Meaning |
|---|---|
path |
The path of the file to read. |
encoding |
Specifies how file content should be decoded, such as UTF-8. It is optional. |
callback |
A function that receives the error, if any, and the file data. |
The callback follows the error-first pattern:
(err, data). If an error occurs,
err contains the error information. Otherwise,
data contains the file content.
3. First Example: Read a Text File
Let's create a simple Node.js application that reads a text file and displays its content.
Step 1: Create a Project Folder
mkdir ReadingFilesDemo
cd ReadingFilesDemo
npm init -y
Step 2: Create message.txt
Create a file named message.txt in the project
folder and add the following content.
Welcome to Node.js!
We are learning how to read files.
CIIT Training Institute
Step 3: Create app.js
const fs = require("fs");
fs.readFile("message.txt", "utf8", (err, data) => {
if (err) {
console.log("Error reading file:", err.message);
return;
}
console.log("File Content:");
console.log(data);
});
Step 4: Run the Program
node app.js
Output:
File Content:
Welcome to Node.js!
We are learning how to read files.
CIIT Training Institute
Explanation:
require("fs")imports the File System module."message.txt"specifies the file to read."utf8"converts the file content into a readable string.(err, data)receives the error and file content.console.log(data)displays the content in the terminal.
4. Why Do We Use UTF-8 Encoding?
When Node.js reads a file without specifying an encoding, the returned content is normally a Buffer. A Buffer represents binary data.
If we want to work with ordinary text, we can specify
"utf8" as the encoding.
Example Without Encoding
const fs = require("fs");
fs.readFile("message.txt", (err, data) => {
if (err) {
console.log(err.message);
return;
}
console.log(data);
console.log("Is Buffer:", Buffer.isBuffer(data));
});
Example output:
<Buffer 57 65 6c 63 6f 6d 65 ...>
Is Buffer: true
The exact Buffer output depends on the content of the file.
Example With UTF-8 Encoding
const fs = require("fs");
fs.readFile("message.txt", "utf8", (err, data) => {
if (err) {
console.log(err.message);
return;
}
console.log(data);
console.log("Is Buffer:", Buffer.isBuffer(data));
});
Output:
Welcome to Node.js!
We are learning how to read files.
CIIT Training Institute
Is Buffer: false
5. Understanding Error Handling
A file-reading operation can fail for several reasons. For example, the file may not exist, the path may be incorrect, or the application may not have permission to read it.
Therefore, we should check the err parameter
before using the file content.
const fs = require("fs");
fs.readFile("unknown.txt", "utf8", (err, data) => {
if (err) {
console.log("Unable to read the file.");
console.log(err.message);
return;
}
console.log(data);
});
If unknown.txt does not exist, the program
displays an error message instead of trying to use missing data.
Example output:
Unable to read the file.
ENOENT: no such file or directory ...
The full error message may vary depending on the operating system and file path.
return statement
stops the current callback from continuing after an error.
6. The fs.readFileSync() Method
The fs.readFileSync() method reads a file
synchronously. The program waits until the file has been read
before moving to the next statement.
Syntax:
fs.readFileSync(path, encoding);
Example
const fs = require("fs");
try {
const data = fs.readFileSync("message.txt", "utf8");
console.log("File Content:");
console.log(data);
console.log("Reading completed.");
} catch (err) {
console.log("Error reading file:", err.message);
}
Output:
File Content:
Welcome to Node.js!
We are learning how to read files.
CIIT Training Institute
Reading completed.
The synchronous method throws an exception when the operation
fails. The try...catch block handles that exception.
| Feature | fs.readFile() | fs.readFileSync() |
|---|---|---|
| Operation | Asynchronous | Synchronous |
| Result handling | Callback | Return value |
| Error handling | Check callback error | Use try...catch |
| Execution | Does not block while waiting for the file operation | Blocks further JavaScript execution until it finishes |
| Typical use | Regular application file operations | Small scripts or cases where blocking is acceptable |
7. Reading a JSON File
JSON files store structured information in a text format.
Node.js can read a JSON file as a string and convert that string
into a JavaScript object using JSON.parse().
Step 1: Create student.json
{
"id": 101,
"name": "Rahul",
"course": "Node.js",
"city": "Pune"
}
Step 2: Read and Parse the JSON
const fs = require("fs");
fs.readFile("student.json", "utf8", (err, data) => {
if (err) {
console.log("Error reading JSON file:", err.message);
return;
}
try {
const student = JSON.parse(data);
console.log("Student ID:", student.id);
console.log("Student Name:", student.name);
console.log("Course:", student.course);
console.log("City:", student.city);
} catch (parseErr) {
console.log("Invalid JSON:", parseErr.message);
}
});
Step 3: Run the Program
node app.js
Output:
Student ID: 101
Student Name: Rahul
Course: Node.js
City: Pune
Here, fs.readFile() reads the file,
JSON.parse() converts the JSON text into a JavaScript
object, and we access individual properties using dot notation.
8. Common Mistakes While Reading Files
| Mistake | Solution |
|---|---|
| Using an incorrect file name | Verify the file name and extension. |
| Placing the file in a different folder | Check the file path relative to the current working directory. |
| Not checking the error parameter | Check err before using data. |
| Forgetting text encoding | Specify "utf8" when a text string is required. |
| Parsing invalid JSON | Use valid JSON syntax and handle parsing errors. |
| Using synchronous reading for large operations in a server | Prefer asynchronous reading when blocking execution is undesirable. |
9. Practice Tasks
Task 1: Read Employee Details
- Create a file named
employee.txt. - Store an employee name, ID, department, and salary in it.
- Read the file using
fs.readFile(). - Display all the content in the terminal.
- Handle the error if the file does not exist.
Expected result: The employee information should appear in the terminal.
Task 2: Read Product JSON
- Create a file named
product.json. - Store product ID, product name, and price as JSON properties.
- Read the file using
fs.readFile(). - Convert the file content using
JSON.parse(). - Display each property separately.
Expected result: Product details should appear as individual values in the terminal.
Summary
Reading files in Node.js allows an application to retrieve
information stored in files. The
fs.readFile() method reads files asynchronously
and provides the result through a callback. Specifying
"utf8" returns readable text instead of a Buffer.
Error handling is important because files may be missing,
inaccessible, or invalid.
The fs.readFileSync() method reads files
synchronously and can be used with try...catch
to handle errors. We also learned how to read a JSON file
and convert its content into a JavaScript object using
JSON.parse(). These techniques are useful for
reading configuration, student records, and other file-based
information in Node.js applications at CIIT Training Institute.