A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/javascript/javascript-program-to-read-text-file/ below:

JavaScript Program to read text File

JavaScript Program to read text File

Last Updated : 11 Jul, 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
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, 
                 initial-scale=1.0">
    <title>Read File in Browser</title>
</head>

<body>
    <input type="file" id="fileInput" />
    <script>
        document.getElementById('fileInput')
            .addEventListener('change', (event) => {
                const file = event.target.files[0];
                const reader = new FileReader();

                reader.onload = function () {
                    const content = reader.result;
                    console.log(content);
                };

                reader.onerror = function () {
                    console.error('Error reading the file');
                };

                reader.readAsText(file, 'utf-8');
            });
    </script>
</body>

</html>
Output:
This is some data inside file Input.txt.

Note: To run the script first make both files in the same folder and then run script.js using NodeJs interpreter in terminal.


Program to read text File in JavaScript


RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4