How to Read Text From a File in Node.js

In this article, we'll learn how to read text from a file using Node.js.

First, make sure you have Node.js installed. If you haven't, visit Node.js official website and download the version suitable for your operating system.

Reading a File

Node.js provides the fs (File System) module to interact with the file system. You can use methods like fs.readFileSync or fs.readFile to read a file. The former is synchronous (blocking), and the latter is asynchronous (non-blocking).

Synchronous Method

The synchronous method, fs.readFileSync, reads the file entirely before moving to the next line of code. If the file is large, this can slow down your application.

Here's how to use it:

const fs = require('fs');

try {
     // Imagine you have a file named 'pokedex.txt' containing Pokémon data
    const data = fs.readFileSync('pokedex.txt', 'utf8');
    console.log(data); // Displays the content of 'pokedex.txt'
} catch (error) {
    console.error('Error reading file:', error);
}

In this example, example.txt is the file you want to read. The file must be in the same directory as your Node.js script, or you should provide the correct path.

Asynchronous Method

The asynchronous method, fs.readFile, is non-blocking. It allows your Node.js app to perform other tasks while reading the file.

Here's an example:

const fs = require('fs');

fs.readFile('pokedex.txt', 'utf8', (error, data) => {
    if (error) {
        console.error('Error reading file:', error);
        return;
    }
    console.log(data);
});

In this case, fs.readFile takes a callback function. This function executes after the file has been read. If there's an error, it will be in the error parameter. Otherwise, the file's contents will be in the data parameter.


Remember, using the synchronous or asynchronous method depends on your application's needs.

And that's it!

You now know the basics of reading text files in Node.js.

Happy coding! ✌️

NodeNodejs
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses; Lead Developer, Software Architect, Product Manager, CTO and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.