How to Read Files using readFile method in Node

Updated onbyAlan Morel
How to Read Files using readFile method in Node

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:

  1. The path of the file to read
  2. The encoding of the file
  3. 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:

hello world

Let's use the readFile() method to read this file:

import 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:

hello 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:

import { 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();
hello 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!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.