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!
- Getting Started with Express
- Create an RSS Reader in Node
- Getting Started with Electron
- How to build a Discord bot using TypeScript
- How to deploy a Deno app using Docker
- Getting Started with Deno
- How to deploy an Express app using Docker
- Learn how to use v-model with a custom Vue component
- Getting Started with Handlebars.js
- Creating a Twitter bot with Node.js
- Using Push.js to Display Web Browser Notifications
- Getting Started with Vuex: Managing State in Vue