首页 > 解决方案 > 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>

标签: javascriptdrag-and-dropfilereader

解决方案


事实证明,它是一个 Unix 的东西,与 javascript 完全无关。无论您是否插入它,无论您的编辑器是否显示它,它似乎总是会以换行符终止。所以发生的事情是我认为我的文件没有换行符,因为我的编辑器没有显示它,而实际上它确实显示了它。

哎呀!


推荐阅读