Languages
[Edit]
EN

Node.js - read file

0 points
Created by:
Gigadude
791

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

Node.js provides file operations API. You can import File System Module (fs) syntax with:

const fs = require("fs")

Note:

fs is a built-in module and you don't need to download it via npm.

Node.js file system module methods have asynchronous and synchronous versions:

  • asynchronous fs.readFile() - recommended,
  • synchronous fs.readFileSync().

1. Asynchronous fs.readFile()

The fs.readFile() method takes in two parameters:

  • path to the file,
  • callback function with two arguments:
    • error,
    • data.

With fs.readFile() method, we can read a file in a non-blocking asynchronous way.

2. Synchronous fs.readFileSync()

The fs.readFileSync() method takes in two parameters:

  • path to the file,
  • options (optional parameter).

With fs.readFileSync() method, we can read files in a synchronous way, blocking other parallel node.js processes and do the current file reading process.

3. Usage example

Below we create file.txt with some text inside and file.js to read the text. Then we simply use: node file.js command in cmd to run our program.

file.txt:

message: dirask is cool.

file.js:

const fs = require('fs'); // imports File System Module

// Asynchronous reading
fs.readFile('file.txt', (error, data) => {
    if (error) {
        return console.error(error);
    }
    console.log('Asynchronous reading - ' + data.toString());
});

// Synchronous reading
const data = fs.readFileSync('file.txt');
console.log('Synchronous reading - ' + data.toString());

console.log('The program is executed. ');

Note:

Create your own file.txt and file.js eg. in Visual Studio Code, then run the script with the following command in the terminal / cmd:

node file.js

Output:

Synchronous reading - message: dirask is cool.
The program is executed. 
Asynchronous reading - message: dirask is cool.

Alternative titles

  1. Node.js - readFile / readFileSync example
  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.
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