JSFiddle - React, Tailwind, and code Playground
HTML
To use this example:
<ol>
<li>Browse for a text file that has 10 characters in it (10 is not a magic number - almost any size works - the important thing is that the file starts bigger and ends smaller)</li>
<li>Observe that the result is an array of 10 items representing the character codes of each item</li>
<li>While this is still running, delete 5 characters from the file and save</li>
<li>Observe that the result is still an array of 10 items - the first 5 are correct but the last 5 are all 90 (capital letter Z)</li>
</ol>
<input type="file" />
<textarea cols="80" rows="10">s</textarea>
JavaScript
function ReadFile() {
var input = document.getElementsByTagName("input")[0];
var output = document.getElementsByTagName("textarea")[0];
if (input.files.length === 0) {
output.value = 'No file selected';
window.setTimeout(ReadFile, 1000);
return;
}
readFileAsArrayBuffer(input.files[0], function(data) {
var array = new Int8Array(data);
output.value = JSON.stringify(array, null, ' ');
window.setTimeout(ReadFile, 1000);
}, function (e) {
console.error(e);
});
}
ReadFile();
function readFileAsArrayBuffer(file, success, error) {
var fr = new FileReader();
fr.addEventListener('error', error, false);
if (fr.readAsBinaryString) {
fr.addEventListener('load', function () {
var string = this.resultString != null ? this.resultString : this.result;
var result = new Uint8Array(string.length);
for (var i = 0; i < string.length; i++) {
result[i] = string.charCodeAt(i);
}
success(result.buffer);
}, false);
return fr.readAsBinaryString(file);
} else {
fr.addEventListener('load', function () {
success(this.result);
}, false);
return fr.readAsArrayBuffer(file);
}
}