Open In App

Javascript | Program to read text File

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

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-requisite:

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

Syntax:

readFile( Path, Options, Callback);

Parameters:

  • path: It takes in relative path from the program to the text File. If both file and program are in the same folder, then simply give the file name of the text file.
  • Options: It is an optional parameter that specifies the data is to be read from the file. If nothing is passed, then the default raw buffer is returned.
  • Callback Function: It is the callback function that has further two arguments (err, data). If the operation fails to extract the data, the error shows what is the fault, and else data argument will contain the data from the file.

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.



Last Updated : 22 Dec, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads