How to load the contents of a text file into a JavaScript variable? - GeeksforGeeks

10 May, 2022
In this article, we will examine how to read the contents of any text file that exists on your computer into a variable using JavaScript. The following are a few basic pointers that everybody should brush through before looking at the code:
Event listeners: These are predefined functions that exist in JavaScript. They take two arguments, the first one is, the event that an element should look for/ listen to and the second one is, the action that the element should perform if the event mentioned in the first argument occurs.
Regular Expressions: A regular expression is a sequence of characters. Every regular expression defines a certain pattern that can be used for multiple purposes. The most common one being, pattern matching. As mentioned above Regular Expressions are most commonly used for pattern matching and after the expected pattern of characters is spotted, many functions can be applied on them, like split(), join(), replace() etc.
Example: In this example we will just create a text area where the text will appear from the text file that has been used as an input in the index.html. The JavaScript code will be able to extract the text from any text file and display it in script.js.
index.html: 
html
<!DOCTYPE html><html> <head>    <title>Text file reading</title>    <meta charset="utf-8">    <meta name="viewport"          content="width=device-width, initial-scale=1.0"> </head><style type="text/css">    div {        display: flex;        flex-direction: column;        align-items: center;    }         input {        margin-top: 10px;    }         textarea {        margin-top: 15px;        width: 70%;    }</style> <body>    <center>        <h1 style="color: green;">          GeeksforGeeks        </h1>        <div>            <input type="file">            <textarea cols="30" rows="20"                      placeholder="text will appear here">            </textarea>        </div>    </center>    <script src="script.js"></script></body> </html>
script.js: 
javascript
let input = document.querySelector('input') let textarea = document.querySelector('textarea') // This event listener has been implemented to identify a// Change in the input section of the html code// It will be triggered when a file is chosen.input.addEventListener('change', () => {    let files = input.files;     if (files.length == 0) return;     /* If any further modifications have to be made on the       Extracted text. The text can be accessed using the       file variable. But since this is const, it is a read       only variable, hence immutable. To make any changes,       changing const to var, here and In the reader.onload       function would be advisible */    const file = files[0];     let reader = new FileReader();     reader.onload = (e) => {        const file = e.target.result;         // This is a regular expression to identify carriage        // Returns and line breaks        const lines = file.split(/\r\n|\n/);        textarea.value = lines.join('\n');     };     reader.onerror = (e) => alert(e.target.error.name);     reader.readAsText(file);});
        
Output:                                              
                                       
JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.
hardikkoriintern
CSS-Misc
HTML-Misc
Picked
CSS
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to apply style to parent if it has child with CSS?
Types of CSS (Cascading Style Sheet)
How to position a div at the bottom of its container using CSS?
Design a web page using HTML and CSS
How to set space between the flexbox ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ?