Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read text file in JavaScript

I am trying to load a text file into my JavaScript file and then read the lines from that file in order to get information, and I tried the FileReader but it does not seem to be working. Can anyone help?

function analyze(){    var f = new FileReader();     f.onloadend = function(){        console.log("success");    }    f.readAsText("cities.txt"); } 
like image 278
CRS Avatar asked Dec 04 '12 18:12

CRS


People also ask

Can HTML read text file?

HTML 5 provides a standard way to interact with local files with the help of File API. The File API allows interaction with single, multiple as well as BLOB files. The FileReader API can be used to read a file asynchronously in collaboration with JavaScript event handling.

How do I read a text file in node JS?

We can use the 'fs' module to deal with the reading of file. The fs. readFile() and fs. readFileSync() methods are used for the reading files.

How do I read a text file in react JS?

To read a text file in React, we can use the FileReader constructor. to define the showFile function that gets the selected file from e. target.


1 Answers

Yeah it is possible with FileReader, I have already done an example of this, here's the code:

<!DOCTYPE html> <html>   <head>     <title>Read File (via User Input selection)</title>     <script type="text/javascript">     var reader; //GLOBAL File Reader object for demo purpose only      /**      * Check for the various File API support.      */     function checkFileAPI() {         if (window.File && window.FileReader && window.FileList && window.Blob) {             reader = new FileReader();             return true;          } else {             alert('The File APIs are not fully supported by your browser. Fallback required.');             return false;         }     }      /**      * read text input      */     function readText(filePath) {         var output = ""; //placeholder for text output         if(filePath.files && filePath.files[0]) {                        reader.onload = function (e) {                 output = e.target.result;                 displayContents(output);             };//end onload()             reader.readAsText(filePath.files[0]);         }//end if html5 filelist support         else if(ActiveXObject && filePath) { //fallback to IE 6-8 support via ActiveX             try {                 reader = new ActiveXObject("Scripting.FileSystemObject");                 var file = reader.OpenTextFile(filePath, 1); //ActiveX File Object                 output = file.ReadAll(); //text contents of file                 file.Close(); //close file "input stream"                 displayContents(output);             } catch (e) {                 if (e.number == -2146827859) {                     alert('Unable to access local files due to browser security settings. ' +                       'To overcome this, go to Tools->Internet Options->Security->Custom Level. ' +                       'Find the setting for "Initialize and script ActiveX controls not marked as safe" and change it to "Enable" or "Prompt"');                  }             }                }         else { //this is where you could fallback to Java Applet, Flash or similar             return false;         }                return true;     }         /**      * display content using a basic HTML replacement      */     function displayContents(txt) {         var el = document.getElementById('main');          el.innerHTML = txt; //display output in DOM     }    </script> </head> <body onload="checkFileAPI();">     <div id="container">             <input type="file" onchange='readText(this)' />         <br/>         <hr/>            <h3>Contents of the Text file:</h3>         <div id="main">             ...         </div>     </div> </body> </html> 

It's also possible to do the same thing to support some older versions of IE (I think 6-8) using the ActiveX Object, I had some old code which does that too but its been a while so I'll have to dig it up I've found a solution similar to the one I used courtesy of Jacky Cui's blog and edited this answer (also cleaned up code a bit). Hope it helps.

Lastly, I just read some other answers that beat me to the draw, but as they suggest, you might be looking for code that lets you load a text file from the server (or device) where the JavaScript file is sitting. If that's the case then you want AJAX code to load the document dynamically which would be something as follows:

<!DOCTYPE html> <html> <head><meta charset="utf-8" /> <title>Read File (via AJAX)</title> <script type="text/javascript"> var reader = new XMLHttpRequest() || new ActiveXObject('MSXML2.XMLHTTP');  function loadFile() {     reader.open('get', 'test.txt', true);      reader.onreadystatechange = displayContents;     reader.send(null); }  function displayContents() {     if(reader.readyState==4) {         var el = document.getElementById('main');         el.innerHTML = reader.responseText;     } }  </script> </head> <body> <div id="container">     <input type="button" value="test.txt"  onclick="loadFile()" />     <div id="main">     </div> </div> </body> </html> 
like image 145
bcmoney Avatar answered Sep 25 '22 05:09

bcmoney