How to read a text file using Node.js?
Ask by Revati S Misra
Updated 01 May 2023
To read a text file 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:
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.