Languages
[Edit]
EN

Node.js - read files

0 points
Created by:
Saim-Mccullough
418

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');

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