Introduction
One of the most common tasks in backend development is reading data from files. Applications frequently read configuration files, log files, JSON data, text files, CSV files, and user-uploaded documents.
Unlike JavaScript running in a web browser, Node.js can directly interact with the computer’s file system through its built-in File System (fs) module. This allows developers to read files without installing any external libraries.
For automation engineers, file reading is an essential skill. Test automation frameworks often read data from CSV, JSON, XML, or text files to perform data-driven testing, load configuration values, compare expected results, generate reports, and validate application behavior.
What is File Reading?
File reading is the process of accessing the contents of a file stored on the computer.
Node.js provides several methods to read files, including:
Reading an entire file
Reading files asynchronously
Reading files synchronously
Reading text files
Reading JSON files
Reading binary files
Why Read Files?
Reading files allows applications to:
Load configuration settings
Read user data
Process CSV files
Read JSON data
Display stored content
Generate reports
Perform data-driven testing
The File System (fs) Module
Node.js includes a built-in module called fs (File System).
Before reading files, import the module:
const fs = require("fs");
No installation is required because it is built into Node.js.
Asynchronous File Reading
The most commonly used method is fs.readFile().
Syntax
fs.readFile(path, encoding, callback);
Parameters
| Parameter | Description |
|---|---|
path | File path |
encoding | File encoding (for example, "utf8") |
callback | Function executed after reading the file |
Example 1: Read a Text File
Assume there is a file named sample.txt containing:
Welcome to Node.js File Handling.
Read the file:
const fs = require("fs");
fs.readFile("sample.txt", "utf8", (error, data) => {
if (error) {
console.log(error);
return;
}
console.log(data);
});
Sample Output
Welcome to Node.js File Handling.
Understanding the Callback
The callback receives two parameters:
(error, data)
errorcontains an error if reading fails.datacontains the file contents if reading succeeds.
Example 2: Handle File Not Found
const fs = require("fs");
fs.readFile("missing.txt", "utf8", (error, data) => {
if (error) {
console.log("File not found.");
return;
}
console.log(data);
});
Sample Output
File not found.
Synchronous File Reading
Node.js also provides fs.readFileSync().
Unlike readFile(), it waits until the file is completely read.
Syntax
const data = fs.readFileSync(path, encoding);
Example 3: Read a File Synchronously
const fs = require("fs");
const data = fs.readFileSync("sample.txt", "utf8");
console.log(data);
Sample Output
Welcome to Node.js File Handling.
Asynchronous vs Synchronous Reading
| Feature | readFile() | readFileSync() |
|---|---|---|
| Blocking | No | Yes |
| Performance | Faster for large applications | Slower because execution waits |
| Uses Callback | Yes | No |
| Recommended | Yes | Only when necessary |
Reading JSON Files
Suppose user.json contains:
{
"name": "John",
"age": 25
}
Read the JSON file:
const fs = require("fs");
fs.readFile("user.json", "utf8", (error, data) => {
if (error) {
console.log(error);
return;
}
const user = JSON.parse(data);
console.log(user.name);
});
Sample Output
John
Real-World Example
Read a configuration file.
config.json
{
"browser": "chrome",
"url": "https://example.com"
}
const fs = require("fs");
fs.readFile("config.json", "utf8", (error, data) => {
if (error) {
console.log(error);
return;
}
const config = JSON.parse(data);
console.log(config.browser);
console.log(config.url);
});
Sample Output
chrome
https://example.com
Automation Testing Example
Reading files is widely used in automation frameworks.
Playwright Example
Read browser configuration.
const fs = require("fs");
const config = JSON.parse(
fs.readFileSync("config.json", "utf8")
);
console.log(config.browser);
Selenium Example
Read test data.
const fs = require("fs");
const users = fs.readFileSync("users.txt", "utf8");
console.log(users);
Cypress Example
Load fixture data.
const fs = require("fs");
const data = fs.readFileSync("testData.json", "utf8");
console.log(JSON.parse(data));
API Testing Example
Read request payload.
const fs = require("fs");
const payload = fs.readFileSync("request.json", "utf8");
console.log(payload);
Data-Driven Testing Example
Read employee data.
const fs = require("fs");
const employees = fs.readFileSync("employees.json", "utf8");
console.log(JSON.parse(employees));
Common Mistakes
Forgetting to Import fs
Incorrect:
fs.readFile("sample.txt");
Correct:
const fs = require("fs");
Forgetting the Encoding
Incorrect:
fs.readFile("sample.txt", (error, data) => {
console.log(data);
});
Without an encoding, the output is a Buffer object instead of readable text.
Correct:
fs.readFile("sample.txt", "utf8", (error, data) => {
console.log(data);
});
Ignoring Errors
Always check the error parameter before using the file data.
Best Practices
Prefer
fs.readFile()for most applications because it is asynchronous.Use
fs.readFileSync()only when blocking behavior is acceptable.Always specify the correct file encoding (such as
"utf8"for text files).Handle file read errors gracefully.
Parse JSON using
JSON.parse()after reading.Keep configuration and test data in separate files.
Use relative or absolute file paths carefully.
Conclusion
Reading files is one of the most important capabilities of Node.js. Using the built-in fs module, developers can easily read text files, JSON files, configuration files, and other resources.
For automation engineers, file reading is fundamental for data-driven testing, configuration management, API payloads, report validation, and automation frameworks.
Mastering file reading is the first step toward effective file handling in Node.js.
Frequently Asked Questions (FAQs)
Which module is used to read files in Node.js?
The built-in fs (File System) module.
How do I import the fs module?
const fs = require("fs");
What is the difference between readFile() and readFileSync()?
readFile()is asynchronous and does not block execution.readFileSync()is synchronous and blocks execution until the file is read.
Why should I specify "utf8" when reading a text file?
Without an encoding, Node.js returns a Buffer instead of a readable string.
How do I read a JSON file?
Read the file as text and then use JSON.parse().
const data = fs.readFileSync("user.json", "utf8");
const user = JSON.parse(data);
Why is file reading important in automation testing?
Automation engineers use file reading to load test data, configuration files, API payloads, expected results, reports, and environment-specific settings.
Key Takeaways
Node.js uses the built-in
fsmodule for file handling.fs.readFile()reads files asynchronously.fs.readFileSync()reads files synchronously.Always specify
"utf8"when reading text files.Handle file read errors properly.
Use
JSON.parse()when reading JSON files.Asynchronous reading is recommended for most applications.
File reading is widely used in Playwright, Selenium, Cypress, API testing, and Node.js applications.
Store configuration and test data in external files for better maintainability.
Mastering file reading is essential for backend development and automation testing.
