Html read text file javascript

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    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. However, all the browsers do not have HTML 5 support so it is important to test the browser compatibility before using the File API. There are four inbuilt methods in the FileReader API to read local files:

    • FileReader.readAsArrayBuffer(): Reads the contents of the specified input file. The result attribute contains an ArrayBuffer representing the file’s data.
    • FileReader.readAsBinaryString(): Reads the contents of the specified input file. The result attribute contains the raw binary data from the file as a string.
    • FileReader.readAsDataURL(): Reads the contents of the specified input file. The result attribute contains a URL representing the file’s data.
    • FileReader.readAsText(): Reads the contents of the specified input file. The result attribute contains the contents of the file as a text string. This method can take encoding version as the second argument(if required). The default encoding is UTF-8.

    In this case we are using FileReader.readAsText() method to read local .txt file.

        Read Text File

        "file" name="inputfile"

                id="inputfile">

        

        

    "output">

        

    Html read text file javascript

    This code prints the content of the input file exactly the same as is there in the input 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.


    I’m trying to implemennt a simple text file reader by creating a function that takes in the file’s path and converts each line of text into a char array, but it’s not working.

    function readTextFile() {
      var rawFile = new XMLHttpRequest();
      rawFile.open("GET", "testing.txt", true);
      rawFile.onreadystatechange = function() {
        if (rawFile.readyState === 4) {
          var allText = rawFile.responseText;
          document.getElementById("textSection").innerHTML = allText;
        }
      }
      rawFile.send();
    }
    

    What is going wrong here?

    This still doesn’t seem to work after changing the code a little bit from a previous revision and now it's giving me an XMLHttpRequest exception 101.

    I’ve tested this on Firefox and it works, but in Google Chrome it just won't work and it keeps giving me an Exception 101. How can I get this to work on not just Firefox, but also on other browsers (especially Chrome)?

    ggorlen

    36.8k7 gold badges61 silver badges76 bronze badges

    asked Jan 21, 2013 at 20:14

    3

    You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

    function readTextFile(file)
    {
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", file, false);
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4)
            {
                if(rawFile.status === 200 || rawFile.status == 0)
                {
                    var allText = rawFile.responseText;
                    alert(allText);
                }
            }
        }
        rawFile.send(null);
    }
    

    And specify file:// in your filename:

    readTextFile("file:///C:/your/path/to/file.txt");
    

    Themroc

    4752 silver badges5 bronze badges

    answered Jan 21, 2013 at 20:20

    Html read text file javascript

    Majid LaissiMajid Laissi

    18.6k18 gold badges65 silver badges105 bronze badges

    29

    After the introduction of fetch api in javascript, reading file contents could not be simpler.

    reading a text file

    fetch('file.txt')
      .then(response => response.text())
      .then(text => console.log(text))
      // outputs the content of the text file
    

    reading a json file

    fetch('file.json')
      .then(response => response.json())
      .then(jsonResponse => console.log(jsonResponse))     
       // outputs a javascript object from the parsed json
    

    Update 30/07/2018 (disclaimer):

    This technique works fine in Firefox, but it seems like Chrome's fetch implementation does not support file:/// URL scheme at the date of writing this update (tested in Chrome 68).

    Update-2 (disclaimer):

    This technique does not work with Firefox above version 68 (Jul 9, 2019) for the same (security) reason as Chrome: CORS request not HTTP. See https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS/Errors/CORSRequestNotHttp.

    OlivierM

    2,57223 silver badges35 bronze badges

    answered Sep 9, 2017 at 9:42

    11

    Visit Javascripture ! And go the section readAsText and try the example. You will be able to know how the readAsText function of FileReader works.

    var openFile = function(event) {
      var input = event.target;
    
      var reader = new FileReader();
      reader.onload = function() {
        var text = reader.result;
        var node = document.getElementById('output');
        node.innerText = text;
        console.log(reader.result.substring(0, 200));
      };
      reader.readAsText(input.files[0]);
    };

    ...

    Html read text file javascript

    Teocci

    5,7121 gold badge42 silver badges42 bronze badges

    answered Mar 20, 2015 at 21:30

    Html read text file javascript

    Amit ChaurasiaAmit Chaurasia

    1,4092 gold badges11 silver badges8 bronze badges

    3

    var input = document.getElementById("myFile");
    var output = document.getElementById("output");
    
    
    input.addEventListener("change", function () {
      if (this.files && this.files[0]) {
        var myFile = this.files[0];
        var reader = new FileReader();
        
        reader.addEventListener('load', function (e) {
          output.textContent = e.target.result;
        });
        
        reader.readAsBinaryString(myFile);
      }   
    });
    
    

    answered Aug 22, 2017 at 10:46

    Html read text file javascript

    3

    Modern solution:

    Use fileOrBlob.text() as follows:

    
    

    When user uploads a text file via that input, it will be logged to the console. Here's a working jsbin demo.

    Here's a more verbose version:

    
    
    

    Currently (January 2020) this only works in Chrome and Firefox, check here for compatibility if you're reading this in the future: https://developer.mozilla.org/en-US/docs/Web/API/Blob/text

    On older browsers, this should work:

    
    
    

    Related: As of September 2020 the new Native File System API available in Chrome and Edge in case you want permanent read-access (and even write access) to the user-selected file.

    2

    Yes JS can read local files (see FileReader()) but not automatically: the user has to pass the file or a list of files to the script with an html .

    Then with JS it is possible to process (example view) the file or the list of files, some of their properties and the file or files content.

    What JS cannot do for security reasons is to access automatically (without the user input) to the filesystem of his computer.

    To allow JS to access to the local fs automatically is needed to create not an html file with JS inside it but an hta document.

    An hta file can contain JS or VBS inside it.

    But the hta executable will work on windows systems only.

    This is standard browser behavior.

    Also Google Chrome worked at the fs API, more info here: http://www.html5rocks.com/en/tutorials/file/filesystem/

    Html read text file javascript

    isherwood

    54.4k15 gold badges105 silver badges147 bronze badges

    answered Jan 29, 2016 at 3:31

    SparrowSparrow

    3313 silver badges3 bronze badges

    0

    Using Fetch and async function

    const logFileText = async file => {
        const response = await fetch(file)
        const text = await response.text()
        console.log(text)
    }
    
    logFileText('file.txt')
    

    answered Jan 8, 2019 at 13:15

    barro32barro32

    2,20420 silver badges34 bronze badges

    2

    Try creating two functions:

    function getData(){       //this will read file and send information to other function
           var xmlhttp;
    
           if (window.XMLHttpRequest) {
               xmlhttp = new XMLHttpRequest();               
           }           
           else {               
               xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");               
           }
    
           xmlhttp.onreadystatechange = function () {               
               if (xmlhttp.readyState == 4) {                   
                 var lines = xmlhttp.responseText;    //*here we get all lines from text file*
    
                 intoArray(lines);     *//here we call function with parameter "lines*"                   
               }               
           }
    
           xmlhttp.open("GET", "motsim1.txt", true);
           xmlhttp.send();    
    }
    
    function intoArray (lines) {
       // splitting all text data into array "\n" is splitting data from each new line
       //and saving each new line as each element*
    
       var lineArr = lines.split('\n'); 
    
       //just to check if it works output lineArr[index] as below
       document.write(lineArr[2]);         
       document.write(lineArr[3]);
    }
    

    Html read text file javascript

    Bill Bell

    20.4k5 gold badges42 silver badges57 bronze badges

    answered Oct 16, 2013 at 23:29

    1

    Provably you already try it, type "false" as follows:

     rawFile.open("GET", file, false);
    

    Html read text file javascript

    A-Sharabiani

    16.3k16 gold badges106 silver badges125 bronze badges

    answered Nov 26, 2013 at 12:17

    momenmomen

    1291 silver badge3 bronze badges

    other example - my reader with FileReader class

    
        
            
            
            
        
        
            
            
            
    Source file

    answered Feb 19, 2015 at 15:35

    Html read text file javascript

    webskywebsky

    2,9421 gold badge33 silver badges29 bronze badges

    1

    This might help,

        var xmlhttp = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
    
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                alert(xmlhttp.responseText);
            }
        }
    
        xmlhttp.open("GET", "sample.txt", true);
        xmlhttp.send();
    

    answered Nov 18, 2016 at 15:20

    Sameera R.Sameera R.

    4,2161 gold badge33 silver badges51 bronze badges

    Local AJAX calls in Chrome are not supported due to same-origin-policy.

    Error message on chrome is like this: "Cross origin requests are not supported for protocol schemes: http, data, chrome, chrome-extension, https."

    This means that chrome creates a virtual disk for every domain to keep the files served by the domain using http/https protocols. Any access to files outside this virtual disk are restricted under same origin policy. AJAX requests and responses happen on http/https, therefore wont work for local files.

    Firefox does not put such restriction, therefore your code will work happily on the Firefox. However there are workarounds for chrome too : see here.

    answered Dec 26, 2018 at 12:12

    Html read text file javascript

    1

    Adding to some the above answers, this modified solution worked for me.

    
    

    ....

    let fileInput  = document.getElementById('file-upload-input');
    let files = fileInput.files;
    
    //Use createObjectURL, this should address any CORS issues.
    let filePath = URL.createObjectURL(files[0]);
    

    ....

    function readTextFile(filePath){
        var rawFile = new XMLHttpRequest();
        rawFile.open("GET", filePath , true);
        rawFile.send(null);
    
        rawFile.onreadystatechange = function (){
            if(rawFile.readyState === 4){
                if(rawFile.status === 200 || rawFile.status == 0){
                    var allText = rawFile.responseText;
                    console.log(allText);
                }
            }
        }     
    }
    

    answered Dec 31, 2018 at 19:50

    FabiiFabii

    3,74013 gold badges49 silver badges89 bronze badges

    function readTextFile(file) {
        var rawFile = new XMLHttpRequest(); // XMLHttpRequest (often abbreviated as XHR) is a browser object accessible in JavaScript that provides data in XML, JSON, but also HTML format, or even a simple text using HTTP requests.
        rawFile.open("GET", file, false); // open with method GET the file with the link file ,  false (synchronous)
        rawFile.onreadystatechange = function ()
        {
            if(rawFile.readyState === 4) // readyState = 4: request finished and response is ready
            {
                if(rawFile.status === 200) // status 200: "OK"
                {
                    var allText = rawFile.responseText; //  Returns the response data as a string
                    console.log(allText); // display text on the console
                }
            }
        }
        rawFile.send(null); //Sends the request to the server Used for GET requests with param null
    }
    
    readTextFile("text.txt"); //<= Call function ===== don't need "file:///..." just the path 
    

    - read file text from javascript
    - Console log text from file using javascript
    - Google chrome and mozilla firefox

    in my case i have this structure of files :

    Html read text file javascript

    the console.log result :

    Html read text file javascript

    answered Jan 18, 2019 at 9:38

    Html read text file javascript

    nadir hamidounadir hamidou

    4232 gold badges7 silver badges18 bronze badges

    1

    If you want to prompt the user to select a file, then read its contents:

    // read the contents of a file input
    const readInputFile = (inputElement, callback) => {
      const reader = new FileReader();
      reader.onload = () => {
        callback(reader.result)
      };
      reader.readAsText(inputElement.files[0]);
    };
    // create a file input and destroy it after reading it
    const openFile = (callback) => {
      var el = document.createElement('input');
      el.setAttribute('type', 'file');
      el.style.display = 'none';
      document.body.appendChild(el);
      el.onchange = () => {readInputFile(el, (data) => {
        callback(data)
        document.body.removeChild(el);
      })}
      el.click();
    }
    

    Usage:

    // prompt the user to select a file and read it
    openFile(data => {
        console.log(data)
      })
    

    answered Dec 16, 2020 at 15:13

    yayayaya

    6,7891 gold badge32 silver badges34 bronze badges

    
    
        
        
        
        
    
    
        
    Select All

    answered Feb 22, 2018 at 7:41

    Get local file data in js(data.js) load:

    function loadMyFile(){
        console.log("ut:"+unixTimeSec());
        loadScript("data.js?"+unixTimeSec(), loadParse);
    }
    function loadParse(){
        var mA_=mSdata.split("\n");
        console.log(mA_.length);
    }
    function loadScript(url, callback){
    
        var script = document.createElement("script")
        script.type = "text/javascript";
    
        if (script.readyState){  //IE
            script.onreadystatechange = function(){
                if (script.readyState == "loaded" ||
                        script.readyState == "complete"){
                    script.onreadystatechange = null;
                    callback();
                }
            };
        } else {  //Others
            script.onload = function(){
                callback();
            };
        }
    
        script.src = url;
        document.getElementsByTagName("head")[0].appendChild(script);
    }
    function hereDoc(f) {
      return f.toString().
          replace(/^[^\/]+\/\*![^\r\n]*[\r\n]*/, "").
          replace(/[\r\n][^\r\n]*\*\/[^\/]+$/, "");
    }
    function unixTimeSec(){
        return Math.round( (new Date()).getTime()/1000);
    }
    

    file of data.js like:

    var mSdata = hereDoc(function() {/*!
    17,399
    1237,399
    BLAHBLAH
    BLAHBLAH
    155,82
    194,376
    */});
    

    dynamic unixTime queryString prevents cached.

    AJ works in web http://.

    answered Apr 26, 2019 at 5:20

    Html read text file javascript

    1

    How to read a local file?

    By using this you will load a file by loadText() then JS will asynchronously wait until the file is read and loaded after that it will execture readText() function allowing you to continue with your normal JS logic (you can also write a try catch block on the loadText() function in the case any error arises) but for this example I keep it at minimal.

    async function loadText(url) {
        text = await fetch(url);
        //awaits for text.text() prop 
        //and then sends it to readText()
        readText(await text.text());
    }
    
    function readText(text){
        //here you can continue with your JS normal logic
        console.log(text);
    }
    
    loadText('test.txt');
    

    answered Oct 3, 2019 at 13:33

    Html read text file javascript

    D.SnapD.Snap

    1,5441 gold badge20 silver badges14 bronze badges

    1

    This function made for browsers and open file picker dialog and after user selection read file as binary and call callback function with read data:

    function pickAndReadFile(callback) {
        var el = document.createElement('input');
        el.setAttribute('type', 'file');
        el.style.display = 'none';
        document.body.appendChild(el);
        el.onchange = function (){
            const reader = new FileReader();
            reader.onload = function () {
                callback(reader.result);
                document.body.removeChild(el);
            };
            reader.readAsBinaryString(el.files[0]);
        }
        el.click();
    }
    

    And use it like this:

    pickAndReadFile(data => {
      console.log(data)
    })
    

    answered Dec 19, 2021 at 8:24

    Html read text file javascript

    MSSMSS

    3,36423 silver badges27 bronze badges

    1

    You can import my library:

    then, the function fetchfile(path) will return the uploaded file

    
    

    Please note: on Google Chrome if the HTML code is local, errors will appear, but saving the HTML code and the files online then running the online HTML file works.

    answered Jan 3, 2019 at 23:40

    In order to read a local file text through JavaScript using chrome, the chrome browser should run with the argument --allow-file-access-from-files to allow JavaScript to access local file, then you can read it using XmlHttpRequest like the following:

    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function () {
       if (xmlhttp.readyState == 4) {
           var allText = xmlhttp.responseText;          
                }
            };
    xmlhttp.open("GET", file, false);
    xmlhttp.send(null);
    

    answered Jan 7, 2019 at 9:56

    Html read text file javascript

    Ali Ezzat OdehAli Ezzat Odeh

    2,0631 gold badge16 silver badges17 bronze badges

    This is an old question but there two main ideas that we have to be clear. Do we want to read the whole file or get it line by line?

    Teo, I want to get the whole file and process it later.

    Okay that is very easy we just call text (remember that text assumes that the file is encoded as UTF-8) and handle the file like this:

    const $output = document.getElementById('output')
    const $file = document.getElementById('file')
    const fetchFile = async e => {
      const [file] = e.target.files
      const text = await file.text()
      $output.textContent = text
    }
    
    $file.onchange = fetchFile

    ...

    What about line by line? It is possible?.

    Well my young Padawan, that is also possible we just need a split the text in lines like this

    const $output = document.getElementById('output')
    const $file = document.getElementById('file')
    let count
    const fetchFile = async e => {
      const [file] = e.target.files
      if (!file) return
      count = 0
      const text = await file.text()
      $output.textContent = text
    
      const lines = text.split(/\r?\n/gm)
      for (const line of lines) {
        if (line) count++
      }
      console.log({count})
    }
    
    $file.onchange = fetchFile

    ...

    answered Sep 28 at 6:36

    Html read text file javascript

    TeocciTeocci

    5,7121 gold badge42 silver badges42 bronze badges

    I know, I am late at this party. Let me show you what I have got.

    This is a simple reading of text file

    var path = "C:\\path\\filename.txt"
    var fs = require('fs')
    fs.readFile(path , 'utf8', function(err, data) {
      if (err) throw err;
      console.log('OK: ' + filename);
      console.log(data)
    });
    

    I hope this helps.

    answered Mar 16, 2020 at 9:50

    1

    How do I read a .text file in JavaScript?

    Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.

    How do I read a local text file in HTML?

    readAsText() method to read local ..
    readAsArrayBuffer(): Reads the contents of the specified input file. ... .
    readAsBinaryString(): Reads the contents of the specified input file. ... .
    readAsDataURL(): Reads the contents of the specified input file..

    How do you call a text file in HTML?

    Make sure you check the source of the document once it's loaded in the browser (all browsers let you do this, right-click "view page source" or similar). If you see the contents of version. txt anywhere in there, you're on the right track, you just need to move it into the body tag so that it will be rendered.

    Can JavaScript read a local file?

    JavaScript cannot typically access local files in new browsers, but the XMLHttpRequest object can be used to read files. So it is actually Ajax (and not Javascript) which is reading the file.