JavaScript Program to read text File (original) (raw)

Last Updated : 10 Jan, 2025

Given a text file, write a JavaScript program to extract the contents of that file. There is a built-in Module or in-built library in NodeJs that handles all the reading operations called fs (File-System). It is basically a JavaScript program (fs.js) where a function for reading operations is written. Import fs-module in the program and use functions to read text from the files in the system.

**Pre-requisites:

How to import a library in JavaScript. Read from here: JavaScript | Importing and Exporting Modules.

**Syntax:

readFile( Path, Options, Callback);

**Parameters:

**Example: Suppose there is a file with the name _Input.txt in the same folder as the JavaScript program.

javascript `

// Requiring fs module in which // readFile function is defined. const fs = require('fs');

fs.readFile('Input.txt', (err, data) => { if (err) throw err;

console.log(data.toString()); });

`

**Example: In this example, we are creating Instead of converting buffer into text using the tostring function, directly get the data into text format also.

HTML `

Read File in Browser