Read A Text File In JavaScript
Last Updated : Mar 11, 2024
IN - JavaScript | Written & Updated By - Amruta
In this article we will show you the solution of read a text file in JavaScript, in HTML, a text file can be uploaded by the user. We will use JavaScript to read the text file.
In order to do that we will use FileReader() function. We will understand this by an example.
Step By Step Guide On Read A Text File In JavaScript :-
Let us see an example to read a text file in JavaScript.
<!DOCTYPE html> <html lang = " en " > <head> <meta charset = " UTF - 8" > <meta http-equiv = " X-UA-Compatible " content = " IE=edge " > <meta name = " viewport " content = " width = device-width , initial-scale = 1.0 " > <title> read a text file in JavaScript </title> <style> h1 { font-size : larger ; font-weight : bolder ; color : lightgreen ; text-align : center ; } div { display : block ; align-items : center ; } </style> </head> <body> <h1> TALKERSCODE </h1> <h3> read a text file in JavaScript </h3> <div> <input type = " file " id = " upload " > <p id = " text " > </p> </div> <script> let upload = document.getElementById ( ' upload ' ) ; let text = document.getElementById ( ' text ' ) ; upload.addEventListener('change', ( ) => { //initialize file reader let reader = new FileReader ( ) ; reader.readAsText (upload.files [ 0 ] ) ; reader.onload = function ( ) { text.innerHTML = reader.result ; } ; } ) ; </script> </body> </html>
- First, we write <! DOCTYPE html> which we used as an instruction to the web browser about what version of HTML file is written in.
- Secondly, the <html> tag is used to indicate the beginning of an HTML document.
- As above now the <head> tag is used to contain information about the web page. In this tag, a <title> tag is used which helps us to specify a webpage title.
- Both <head> and <title> tags are Paired tags. So, both have </head> and </title> ending tags respectively.
- Thirdly, the <body> tag is used to define the webpage body. All the contents to show on the website are written here.
- <h1> tag used to add heading here.
- To add JavaScript Create a <script> tag.
- By using document.getElementById , we access both ‘input’ file and the ‘p’ tag by the Id name.
- Use .addEventListener tag to get an event to be done.
- To initialize the file reader create a variable named ‘ reader ‘ and use FileReader() tag to read the file that was uploaded.
- Use .readAsText to read the uploaded file as a string.
- .onload is used to load the object within the page.
- Using .result to Display the text file.
Conclusion :-
At last here in conclusion, here we can say that with this article’s help, we can read a text file in JavaScript.
I hope this article on read a text file in JavaScript helps you and the steps and method mentioned above are easy to follow and implement.