Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • JS Tutorial
  • JS Exercise
  • JS Interview Questions
  • JS Array
  • JS String
  • JS Object
  • JS Operator
  • JS Date
  • JS Error
  • JS Projects
  • JS Set
  • JS Map
  • JS RegExp
  • JS Math
  • JS Number
  • JS Boolean
  • JS Examples
  • JS Free JS Course
  • JS A to Z Guide
  • JS Formatter
Open In App
Next Article:
JavaScript Program to read text File
Next article icon

JavaScript Program to read text File

Last Updated : 10 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
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-requisites:

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.


Next Article
JavaScript Program to read text File

I

imdhruvgupta
Improve
Article Tags :
  • Technical Scripter
  • JavaScript
  • Web Technologies
  • Technical Scripter 2018
  • File Handling

Similar Reads

    Ways to Read Input from Console in Java
    In Java, there are four different ways to read input from the user in the command line environment(console). 1. Using Buffered Reader ClassBuffered Reader Class is the classical method to take input, Introduced in JDK 1.0. This method is used by wrapping the System.in (standard input stream) in an I
    5 min read
    Automatic Resource Management in Java ( try with resource statements )
    Java provides a feature to make the code more robust and to cut down the lines of code. This feature is known as Automatic Resource Management(ARM) using try-with-resources from Java 7 onwards. The try-with-resources statement is a try statement that declares one or more resources.  This statement e
    5 min read
    BufferedReader Class lines() method in Java with Examples
    BufferedReader.lines() is the method of the Java Buffered Reader Class in the Java Library which returns lines in terms of Stream and from this Buffered Reader class. With the help of the stream, there are a lot of methods that mimic the output according to our needs. Syntax: BufferedReader.lines()
    2 min read
    Convert byte[] array to File using Java
    As we know whenever it comes to writing over a file, write() method of the File class comes into play but here we can not use it in order to convert that byte into a file. In order to convert a byte array to a file, we will be using a method named the getBytes() method of String class. Implementatio
    3 min read
    Java Program to Convert InputStream to String
    Read and Write operations are basic functionalities that users perform in any application. Every programming language provides I/O streams to read and write data. The FileInputStream class and FileOutputStream class of Java performs I/O operations on files. The FileInputStream class is used to read
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences