How to Read Files using readFile method in Node
Table of Contents
As Node is a server-side language, it has the ability to perform file system operations just like any other programming language.
One of the most common file system operations is reading files from the disk.
In this article, we will learn how to read files in Node asynchronoulsy.
Reading Files using readFile()
The recommended way to read files in Node is using the readFile()
method which is part of the fs
module.
This method takes three arguments:
- The path of the file to read
- The encoding of the file
- A callback function that will be called when the file is read
Let's say you have a file called example.txt
with this content inside:
BASHhello world
Let's use the readFile()
method to read this file:
JAVASCRIPTimport fs from "fs";
fs.readFile("example.txt", "utf8", (err, data) => {
if (err) {
console.error(err);
}
console.log(data);
});
When you run this code, you will see the following output:
BASHhello world
Now, this example shows how to read a file using callbacks, however, a more recommended way to read files is using promises so we can take advantage of the async/await syntax.
Here's the same example as above converted to using promises:
JAVASCRIPTimport { promises as fs } from "fs";
const main = async () => {
try {
const data = await fs.readFile("example.txt", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}
};
main();
BASHhello world
When we use promises, we no longer need to include a callback function as the third argument.
The reason why this is recommended is because it is easier to read and understand.
Using await/async means we can avoid callbacks, which can make the code more difficult to read.
Conclusion
In this post, we learned how to read files in Node asynchronously.
Simply use the readFile()
method from the fs
module to read files in Node.
Thanks for reading!
- How to Install Node on Windows, macOS and Linux
- Getting Started with Solid
- Getting Started with Svelte
- Create an RSS Reader in Node
- How to deploy a Node app using Docker
- Build a Real-Time Chat App with Node, Express, and Socket.io
- Getting Started with Moment.js
- Creating a Twitter bot with Node.js
- Getting Started with React
- Setting Up a Local Web Server using Node.js
- Using Axios to Pull Data from a REST API
- How To Create a Modal Popup Box with CSS and JavaScript