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.
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 >
|
javascript
let input = document.querySelector( 'input' )
let textarea = document.querySelector( 'textarea' )
input.addEventListener( 'change' , () => {
let files = input.files;
if (files.length == 0) return ;
const file = files[0];
let reader = new FileReader();
reader.onload = (e) => {
const file = e.target.result;
const lines = file.split(/\r\n|\n/);
textarea.value = lines.join( '\n' );
};
reader.onerror = (e) => alert(e.target.error.name);
reader.readAsText(file);
});
|

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.
Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape,
GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out -
check it out now!
Last Updated :
10 May, 2022
Like Article
Save Article