A JavaScript beginner here. I would like to write a basic function that takes a path to a local text file and returns its contents. I am aware that this question has been asked like 1000 times now, for example here. But every single answer is different from each other, I have tried a few, and they don't seem to work. After googling for a bit, I was able to come up with the following solution
function readTextFile(path) {
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
console.log("File contents: " + contents);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
var file = new File([path], { type: 'plain/text' });
reader.readAsText(file);
return contents
}
However, for some reason it outputs the path itself, not the contents. Please suggest how this code can be fixed, shortened, improved.
I also tried fetch but I get the infamous cross-origin request error, that I could not figure out how to solve easily.
EDIT:
Ok, I'll add a few more lines to make things more clear
index.html:
<input type="file" id="jsonAddressInput" value="enter address here">
script.js
function myFunction() {
var addressField = document.getElementById("jsonAddressInput");
var addressText = addressField.value;
console.log(addressText);
var textContentsOfFile = readTextFile(addressText)
//console.log(textContentsOfFile)
}
function readTextFile(path) {
var reader = new FileReader();
reader.onload = function(event) {
var contents = event.target.result;
console.log("File contents: " + contents);
};
reader.onerror = function(event) {
console.error("File could not be read! Code " + event.target.error.code);
};
var file = new File([""], path, { type: 'plain/text' });
reader.readAsText(file);
return contents
}
It was mentioned that I can use the results of the to get file contents. Please suggest how to fix