Reputation: 295
I have a 1GB file with text data. I need to load 100 bytes starting from N byte using browsers JavaScript into the memory. How do I do that?
Upvotes: 2
Views: 841
Reputation: 19372
Use File API:
function fileReaderApiSupported() {
return (window.File && window.FileReader && window.FileList && window.Blob);
}
function readNBytesOfFile(size, inputId) {
if (!fileReaderApiSupported()) {
alert('FileReader API unsupported');
return;
}
var readFrom = document.getElementById(inputId);
if (!readFrom || !readFrom.files || !readFrom.files.item(0)) {
alert('No file');
return;
}
var countOfBytesToRead = parseInt(size);
var readFromFile = readFrom.files.item(0);
var fileReader = new FileReader();
var chunk = readFromFile.slice(0, countOfBytesToRead);
fileReader.onload = function() {
var result = fileReader.result;
document.getElementById('result').innerText = result;
};
fileReader.readAsText(chunk);
}
<input id="my-file-input" type="file">
<button onclick="readNBytesOfFile(100, 'my-file-input')">READ</button>
<hr/>
<div id="result"></div>
also You can use LineReader to read by chunk and stop reading after 100 bytes.
Upvotes: 2