Languages
[Edit]
EN

Node.js - read files

0 points
Created by:
Saim-Mccullough
688

In this article, we would like to show you how to read files in Node.js.

Below we will present 3 methods to read files in node.js:

  • synchronously,
  • asynchronously with callback,
  • asynchronously with async/await.

Synchronously

Is recommended to use synchronous operations when we want to get better performance - e.g. Node JS-based sequential scripts run under the operating system.

const fs = require('fs');

const data = fs.readFileSync('/path/to/file.txt','utf8');
console.log(data);

Asynchronously with callback

Note:

In the fs.readFile() method, we must provide an absolute path to the file.

const fs = require('fs');

fs.readFile('/path/to/file.txt', 'utf8', (error, data) => { // encoding parameter is optional
        if (error) throw error;
        console.log(data);
    }
);

Asynchronously with async/await

const { readFile } = require('fs/promises');

const readFileAsync = async (path) => {
    try {
        const data = await readFile(path, 'utf-8'); // encoding parameter is optional
        console.log(data);
    } catch (error) {
        console.error(error);
    }
};

readFileAsync('/path/to/file.txt');

Alternative titles

  1. Node.js - how to read files
  2. Node.js - read txt file
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Node.js - file system module

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join