Monday, June 3, 2024

Reading a File in Node.js

The fs module in Node.js provides functions to work with the file system. Using fs module functions you can create file, read file, write to a file, append to a file, delete a file and do many other I/O tasks. In this article we'll see how to read a file in Node.js using methods of fs module.

How to read file in Node.js

In the fs module there are two methods to read a file.

fs.readFile()- This functions reads the file content in a non-blocking, asynchronous manner. A callback function is provided which is called when the file read operation is completed.

fs.readFileSync()- It is the synchronous version of fs.readFile() which means it is a blocking function. Function returns the contents of the file.

Apart from these two methods there is also a readFile() function in the fs.promises API which asynchronously reads the entire contents of a file and returns a Promise object which is resolved with the contents of the file. Thus, you don't need a callback function.

Using fs.readFile()

Syntax of fs.readFile() method is as given below

fs.readFile(file[, options], callback)

The three parameters are described below-

  1. file- This is the filename or file descriptor
  2. options- The optional options argument can be a string specifying an encoding (for example ‘utf8’), or an object with an encoding property specifying the character encoding and a flag with default as 'r' which indicates open file for reading. If both values are passed as an object then it will be like this {encoding: 'utf8', flag: 'r'}.
  3. callback function- A function that is called when the file operation completes. The callback function is passed two arguments (err, data).
    • err- Encapsulates the error, if any, while reading the file.
    • data- Contents of the file.

fs.readFile () Example

const fs = require('fs');
const path = require('path');

fs.readFile(path.join(__dirname, 'Hello.txt'), 'utf8', (err, data)=>{
    if(err){
        console.error('Error while reading file', err);
        return;
    }
    console.log(data);     
});

On running this example file, it should display the content of the passed file on the console.

Using fs.readFileSync()

Syntax of fs.readFileSync() method is as given below

fs.readFile(file[, options])

Description of parameters is same as in readFile() method.

fs.readFileSync() Example

const fs = require('fs');
const path = require('path');

const data = fs.readFileSync(path.join(__dirname, 'Hello.txt'), {encoding: 'utf8', flag: 'r'})
console.log(data);

Using fsPromises.readFile()

Syntax of fsPromises.readFile() method is as given below

fsPromises.readFile(file, options)

The parameters are described below-

  1. file- This is the filename or file descriptor
  2. options- The optional options argument can be a string specifying an encoding (for example ‘utf8’), or an object with an encoding property specifying the character encoding and a flag with default as 'r' which indicates open file for reading. If both values are passed as an object then it will be like this {encoding: 'utf8', flag: 'r'}.

This method returns a Promise so async/await can be used to make the code more readable.

fsPromises.readFile() Example

const fs = require('fs');
const fsPromises = fs.promises;
const path = require('path');

async function readFile(filePath) {
  try {
    const data = await fsPromises.readFile(filePath, { encoding: 'utf8' });
    console.log(data);
  } catch (err) {
    console.log(err);
  }
}

readFile(path.join(__dirname, 'Hello.txt'));

That's all for this topic Reading a File in Node.js. If you have any doubt or any suggestions to make please drop a comment. Thanks!


Related Topics

  1. NodeJS Event Loop
  2. Node.js Event Driven Architecture
  3. NodeJS Blocking Non-blocking Code

You may also like-

  1. Creating HTTP server in Node.js
  2. How to Setup a Node.js Project
  3. How to Add Bootstrap to Angular Application
  4. Angular Pipes With Examples
  5. JavaScript Rest Parameter
  6. Find All Permutations of a Given String Java Program
  7. pass Statement in Python
  8. Spring Boot Microservice Example Using FeignClient