Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html5 fileReader -- how to only read the first N characters of a file?

Tags:

Currently I use a pattern like the following to read the first 3 characters of a series of files:

var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
  var fr = new FileReader();
  fr.onload = function(e) { 
    var first_three_chars = e.target.result.substr(0,3);
  }
  fr.readAsText(f);
}

The trouble is that I'm only interested in the first 3 characters of the file, whereas this method reads the entire file, wasting lots of memory and time. How can I quickly iterate over the files, simply taking quick peeks at the first characters?

Edit: slice() was the answer, thanks sshen. Here's how I did it:

var files = e.dataTransfer.files;
for (var i = 0, f; f = files[i]; i++) {
  var fr = new FileReader();
   fr.onloadend = function(e) {
    if (e.target.readyState == FileReader.DONE) {
      var first_three_chars = e.target.result;
    }
  };
  var blob = f.slice(0, 3);
  fr.readAsText(blob);
}
like image 978
Stu Blair Avatar asked Feb 12 '13 21:02

Stu Blair


2 Answers

You can use the .slice method. You can read more here

var reader = new FileReader();

reader.onloadend = function(evt) 
{
    if (evt.target.readyState == FileReader.DONE)  // DONE == 2
    {
        alert(evt.target.result);
    }
};

var blob = file.slice(start, stop + 1);
reader.readAsBinaryString(blob);
like image 52
NoodleFolk Avatar answered Sep 30 '22 07:09

NoodleFolk


Not enough rep to comment, so putting some warnings about @Stu Blair solution here: With the Blob.slice method you are taking the bytes from the Blob, not the characters.

For example, this won't work:

const blob = new Blob(['😀'], {type: 'text/plain'});
const fr = new FileReader();
fr.readAsText(blob); // Fine, fr.result will be '😀'
fr.readAsText(blob.slice(0, 2)); // Not good, fr.result will be '��'

You will have to use FileReader.readAsArrayBuffer to get the bytes. If your encoding is something like utf-8 you will have to read from the beginning.

like image 30
user7132587 Avatar answered Sep 30 '22 07:09

user7132587