Skip to content

Instantly share code, notes, and snippets.

@jiyu3
Last active March 6, 2018 01:31
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jiyu3/a716a49cc600f048293c081944c13930 to your computer and use it in GitHub Desktop.
Save jiyu3/a716a49cc600f048293c081944c13930 to your computer and use it in GitHub Desktop.
Javascriptで巨大なテキストファイルを少しずつ読み込む ref: https://qiita.com/jiyu/items/3e29959758de497850b9
readBigTextForEachLine = (file, callback, chunk_size = 1024) => {
let offset = 0;
let text = "";
let slice = "";
let fr = new FileReader();
fr.onload = (event) => {
if(typeof fr.result === "string") {
callback(text + fr.result.replace(/\r/g, "\n"));
return true;
}
let view = new Uint8Array(fr.result);
for(let i=0, l=view.length; i<l; i++) {
if(view[i] === 13) { // \n = 10 and \r = 13
if(view[i+1] === 10) {
i++;
}
callback(text + "\n");
text = "";
continue;
}
text += String.fromCharCode(view[i]);
}
seek();
};
fr.onerror = () => {
callback("Failed to read file.");
};
let seek = () => {
if (offset + chunk_size >= file.size) {
slice = file.slice(offset);
fr.readAsText(slice);
} else {
slice = file.slice(offset, offset + chunk_size);
fr.readAsArrayBuffer(slice);
}
offset += chunk_size;
}
seek();
}
<script>
document.getElementById("upload").onchange = (e) => {
let file = e.target.files[0];
readBigTextForEachLine(file, console.log);
};
</script>
<html><body>
Upload Big File: <input type="file" id="upload">
</body></html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment