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 "node: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
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a Node app using Docker
How to Scrape the Web using Node.js and Puppeteer
Getting User Location using JavaScript's Geolocation API
Creating a Twitter bot with Node.js
Using Push.js to Display Web Browser Notifications
Using Axios to Pull Data from a REST API
