Reputation: 378
I'm trying to use FileReader to load dropped files, but there is a mysterious '\n' character being appended to the file if it does not terminate with one.
Drop a text file that does not terminate with a line break and see that the last character of the file will be a '\n' (code 10).
let fileReader = new FileReader();
fileReader.onload = function(event) {
let lastChar = this.result.charCodeAt(this.result.length - 1);
document.querySelector("#last_char").innerText = lastChar;
document.querySelector("#length").innerText = this.result.length;
for (let i = 0; i < this.result.length; ++i) {
console.log(this.result.charCodeAt(i));
}
}
function drop(event) {
event.stopPropagation();
event.preventDefault();
var files = event.dataTransfer.files; //It returns a FileList object
for (var i = 0; i < files.length; i++) {
var file = files[i];
fileReader.readAsText(file);
}
}
* {
box-sizing: border-box;
}
html,
body {
height: 100%;
}
#drop_area {
width: 100%;
height: 50%;
border: 3px dashed #aaaaaa;
border-radius: 10px;
text-align: center;
}
<div id="drop_area" ondrop="drop(event)" ondragover="event.preventDefault()">drop a text file here</div>
<div>Last char:</div>
<div id="last_char"></div>
<div>Length:</div>
<div id="length"></div>
Upvotes: 1
Views: 358
Reputation: 378
It turns out that it is a Unix thing, unrelated with javascript at all. It seem that it will always terminate with a line break, whether you insert it or not, whether your editor shows it or not. So what was happening is that I was thinking my file didn't have a line break, because my editor was not showing it, when in fact it did.
Whoops!
Upvotes: 2