Sometimes, we want to see the result of readAsText()
with HTML5 JavaScript File API.
In this article, we’ll look at how to see the result of readAsText()
with HTML5 JavaScript File API.
See the Result of readAsText() with HTML5 JavaScript File API
To see the result of readAsText()
with HTML5 JavaScript File API, we can get the data from the onload
callback.
For instance, we write:
<input type='file'>
to add a file input.
Then we write:
const fr = new FileReader();
fr.onload = (e) => {
console.log(e.target.result)
};
const input = document.querySelector('input')
input.addEventListener('change', (e) => {
const [file] = e.target.files
fr.readAsText(file);
})
to create a FileReader
instance and assign it to fr
.
Then we set the fr.onload
property to a function that gets the text with e.target.result
and log it with console.log
.
Next, we select the input with document.querySelector
.
Then we call input.addEventListener
with 'change'
to add a change event listener.
The change
event is emitted when we select a file.
In the event handler callback, we get the selected files with e.target.files
.
Then we call fr.readAsText
with file
to read the file
‘s content as text.
Therefore, when we select a text file with the file input, we see the text display in the console.
Conclusion
To see the result of readAsText()
with HTML5 JavaScript File API, we can get the data from the onload
callback.