Skip to content
Fix Code Error

How to read a local text file?

March 13, 2021 by Code Error
Posted By: Anonymous

I’m trying to write 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)?

Solution

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");
Answered By: Anonymous

Related Articles

  • How do i update a javascript variable as its value changes?
  • Synchronous XMLHttpRequest on the main thread is…
  • How to convert image into byte array and byte array…
  • Why doesnt my table sort my div variable in numerical order?
  • Read a local text file using Javascript
  • no match for ‘operator
  • What are the new features in C++17?
  • Fastest way to iterate over all the chars in a String
  • assign flexbox cells the same width
  • How does PHP 'foreach' actually work?
  • How do I include certain conditions in SQL Count
  • Disabling a button upon condition in Google App script
  • How to read data From *.CSV file using javascript?
  • Can't find why this datetime test fails, in F#
  • problem with client server unix domain stream…
  • Javascript validate all checkboxes are selected
  • Getting weird compilation error in defining a…
  • how to use canvas in JavaScript flappy bird code
  • Avoid using document.getElementById with Backbone.js
  • How to create a game over screen for a basic HTML/JS game?
  • load scripts asynchronously
  • Merging multiple PDFs using iTextSharp in c#.net
  • Throw HttpResponseException or return…
  • What's the best way to get the last element of an…
  • Simplest way to create Unix-like continuous pipeline…
  • How to read text file in JavaScript
  • How to remove MySQL completely with config and…
  • Generate new observations based on IF statement R
  • Is it possible to apply CSS to half of a character?
  • For-each over an array in JavaScript
  • Append text to textarea with javascript
  • Pure JavaScript equivalent of jQuery's $.ready() -…
  • Why does my instance of Axios not return the…
  • Basic Ajax send/receive with node.js
  • How to get the response of XMLHttpRequest?
  • What is an IndexOutOfRangeException /…
  • Call php function from JavaScript
  • JavaScript TypeError: Cannot read property 'style' of null
  • C threads corrupting each other
  • javascript minesweeper issue with revealing tiles…
  • LNK2019 símbolo externo public: bool __thiscall ……
  • Why is php POST array empty for me in one instance…
  • How can I center all my contents in html?
  • Do you (really) write exception safe code?
  • I made a game it should display two images when i…
  • I'm trying to take inputs from an HTML form and pass…
  • Using setInterval for creating animation
  • XMLHttpRequest (Ajax) Error
  • C++ Custom Exception classes
  • How to pass the XMLHttpRequest responseText in a Vue…
  • coercing to Unicode: need string or buffer, NoneType…
  • Displaying the Dates that user have chosen from date input
  • showing record text with red color when click stop button
  • Pythonically add header to a csv file
  • Improve INSERT-per-second performance of SQLite
  • How can I pass a wct test while rearranging children…
  • Simple pagination in javascript
  • Maximum XOR With an Element From Array | Leetcode
  • What are the undocumented features and limitations…
  • Postgres could not connect to server
  • How to avoid "module not found" error while calling…
  • Pandas pivot_table: filter on aggregate function
  • How do I print out the contents of a vector?
  • Basic Authentication Using JavaScript
  • Polymer CSS inline elements alignment
  • How can I update specific parts of a text file in java?
  • Polymer data binding with Javascript and attributes
  • My php file shows filtered response but responseText…
  • Reverting to a previous revision using TortoiseSVN
  • Uncaught TypeError: Cannot read property 'value' of null
  • Js Calculation based on radio button, and some problems
  • WAVE file unexpected behaviour
  • Why does C++ code for testing the Collatz conjecture…
  • How do I solve this error, "error while trying to…
  • How can I throw CHECKED exceptions from inside Java…
  • How to add fade animation for this tab
  • Can anyone explain what JSONP is, in layman terms?
  • Simple C example of doing an HTTP POST and consuming…
  • Unable to set variable based on JSON Output
  • How to get the real and total length of char * (char array)?
  • How to properly make a http web GET request
  • setTimeout function not working : javascript
  • Is there any possible way to loop strcmp function in…
  • Ukkonen's suffix tree algorithm in plain English
  • JS file is not updating to new id values
  • How do I upgrade revision in emberjs DS.Store
  • Parsing JSON from XmlHttpRequest.responseJSON
  • Countdown timer goes into negative numbers instead…
  • Setting DIV width and height in JavaScript
  • How to create a plugin for an application written in…
  • Sending a JSON to server and retrieving a JSON in…
  • Sorting 1 million 8-decimal-digit numbers with 1 MB of RAM
  • How do I keep only the first map and when the game…
  • What's wrong with 'template int compare(char p1 [N],…
  • Flappy bird code not working - JavaScript
  • Saving data to a file in C#
  • Generated row of table event listener not working instantly
  • how to get the df names and first input value for…
  • What is a NullReferenceException, and how do I fix it?
  • SpringBootApp NullPointerException with @Autowired…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

How do I install and use curl on Windows?

Next Post:

What does in XML mean?

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error