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 Svelte
Best Visual Studio Code Extensions for 2022
How to build a Discord bot using TypeScript
How to deploy a Deno app using Docker
Using Puppeteer and Jest for End-to-End Testing
Getting Started with Moment.js
Learn how to build a Slack Bot using Node.js
Building a Real-Time Note-Taking App with Vue and Firebase
Getting Started with React
Setting Up a Local Web Server using Node.js
How To Create a Modal Popup Box with CSS and JavaScript
