user2014905 user2014905 - 19 days ago 14
Javascript Question

Javascript read text file from current directory

How to read text file (text1.txt) from current directory using javascript without jquery. I tried the following code.

var file = "text1.txt";
var reader = new FileReader();
var result = reader.readAsText(file);
console.log(result);

Answer

The FileReader API is usually used to read files selected via the an <input type="file">. It cannot read arbitrary files. The readAsText method expects to receive with a Blob or a File object, not a string containing a file name.

To read files that are siblings of the HTML document, use XMLHttpRequest. This will reliably work if you load the document over HTTP(S). If you are using a local HTML document (via a file: URI) then security restrictions in many browsers will prevent it from working (and you should run a local web server instead).

Comments