Read local txt file in javascript


What do you think of this code for reading local files with javascript.
To me it hangs on “onreadystatechange”.

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

Bye bye

Hi @UfoRiccardo

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

You can’t access a local file like that with javascript through the browser (for security reasons). You have to use the FileReader API and the user has to actively pick the file. If you are using node though then you should be able to access a local file.

1 Like

My understanding is that you use XMLHttpRequest to exchange data with the server. According to the XMLHttpRequest documentation:

XMLHttpRequest (XHR) objects are used to interact with servers. You can retrieve data from a URL without having to do a full page refresh. This enables a Web page to update just part of a page without disrupting what the user is doing.

So I am not exactly sure whether it is possible to use it to read local files on your computer. However, there are ways of doing so from the browser. You can read the article below:

nibble, Thanks :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face:

thanks :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face: :slightly_smiling_face:

nibble, thanks :+1: :+1: :+1: :+1: :+1: :+1: :slightly_smiling_face: :slightly_smiling_face:

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.