jordi alba
jordi alba

Reputation: 21

Javascript readfile with filename

I want read file with filename But function gives me error

    var data = "class.php"
    var reader = new FileReader();
    var result  = reader.readAsText(data);
    console.log(result);

Upvotes: 1

Views: 428

Answers (1)

Ran Turner
Ran Turner

Reputation: 18156

JavaScript can read local files using the FileReader() but not automatically, meaning that the user has to pass the file (or a list of files) to the script with an html <input type="file">.

After that, JavaScript will be able to process the file (or list of files).

JavaScript cannot access the filesystem of your computer for security reasons without the user input.

So, if you want to it, you will need to create an html document having that html input and then read the file content.

Then, you can handle the file in the click event handler like so:

var fr = new FileReader();
fr.onload = function(e) {
   const text = e.target.result;
};
fr.readAsText(file);

readAsText is asynchronous, you will need to use the onload callback to see the result.

Upvotes: 1

Related Questions