---
title: "How to read a text file using Node.js?"  
description: "How to read a text file using Node.js?"  
author: "Revati S Misra"  
published: 2023-04-29  
updated: 2023-05-01  
canonical: https://www.mindstick.com/forum/158084/how-to-read-a-text-file-using-node-js  
category: "node.js"  
tags: ["javascript", "node js"]  
reading_time: 2 minutes  

---

# How to read a text file using Node.js?

How to read a [text file](https://www.mindstick.com/forum/12828/converting-a-text-file-to-an-array-in-java) using [Node.js](https://www.mindstick.com/articles/1499/upload-and-download-file-in-node-js)?

## Replies

### Reply by Aryan Kumar

To read a [text](https://www.mindstick.com/blog/301635/did-people-reinvent-texting-to-express-the-full-range-of-emotions) [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) using Node.js, you can use the built-in **fs** (file system) module. The **fs** module provides various methods for interacting with the file system, including reading and writing files. Here's an example of how to read a text file in Node.js:

```javascript
const fs = require('fs');
fs.readFile('path/to/file.txt', 'utf8', function(err, data) {
 if (err) throw err;
 console.log(data);
});
```

In this example, we use the **readFile** method of the **fs** module to read the contents of a file. The first argument is the path to the file we want to read. The second argument specifies the encoding for the file, which in this case is **'utf8'** to read the file as a text file.

The **readFile** method is asynchronous, so we pass a callback function as the third argument. This callback function is called when the file has been read, and it receives two arguments: an error object (if there was an error), and the contents of the file as a string.

In the callback function, we check for errors and throw an exception if there is one. Otherwise, we log the contents of the file to the console. Note that the contents of the file will be printed as a single string. If you want to read the file line-by-line or perform other operations on it, you will need to process the data accordingly.


---

Original Source: https://www.mindstick.com/forum/158084/how-to-read-a-text-file-using-node-js

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
