javascript - Why is FileReader appending line break to files?
问题描述
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>
解决方案
事实证明,它是一个 Unix 的东西,与 javascript 完全无关。无论您是否插入它,无论您的编辑器是否显示它,它似乎总是会以换行符终止。所以发生的事情是我认为我的文件没有换行符,因为我的编辑器没有显示它,而实际上它确实显示了它。
哎呀!
推荐阅读
- algorithm - 以特定模式生成 NXN 矩阵
- jquery - Jquery UI Draggable element top问题由于位置相对
- gitlab - 如何将 sapper/svelte 站点部署到 Gitlab Pages?
- google-cloud-platform - 谷歌云翻译 API 问题
- javascript - 填写表格时可点击提交按钮
- ruby-on-rails - Savon 的存根请求
- python - 无法调整 QFrame 的大小
- c# - 文件的输入验证
- node.js - 使用 Kubernetes 部署 Mongodb 和 NodeJS
- postgresql - 如何删除 DSpace 6x 中生成的比特流?