title: Read n lines of a big text file
body: <p>The smallest file I have has > 850k lines and every line is of unknown length. The goal is to read <code>n</code> lines from this file in the browser. Reading it fully is not going to happen.</p>
  
  <p>Here is the HTML <code>&lt;input type="file" name="file" id="file"&gt;</code> and the JS I have:</p>
  
  <pre><code>var n = 10;
  var reader = new FileReader();
  reader.onload = function(progressEvent) {
    // Entire file
    console.log(this.result);
  
    // By lines
    var lines = this.result.split('\n');
    for (var line = 0; line &lt; n; line++) {
      console.log(lines[line]);
    }
  };
  </code></pre>
  
  <p>Obviously, the problem here is that it tries to first real the whole file and then split it by newline. So no matter of <code>n</code>, it will <em>try</em> to read the whole file, and eventually read nothing when the file is big.</p>
  
  <p>How should I do it?</p>
  
  <p>Note: I am willing to delete the whole function and start from scratch, given that I will be able to <code>console.log()</code> every line that we read.</p>
  
  <hr>
  
  <p>*"every line is of unknown length" -> means that the file is something like this:</p>
  
  <pre><code>(0, (1, 2))
  (1, (4, 5, 6))
  (2, (7))
  (3, (8))
  </code></pre>
  
  <hr>
  
  <p>Edit:</p>
  
  <p>The way to go would be something like <a href="https://stackoverflow.com/questions/25810051/filereader-api-on-big-files">filereader api on big files</a>, but I can't see how I can modify that to read <code>n</code> lines of the file...</p>
  
  <p>By using <a href="https://stackoverflow.com/questions/8936984/uint8array-to-string-in-javascript">Uint8Array to string in Javascript</a> too, one can do from there:</p>
  
  <pre><code>var view = new Uint8Array(fr.result);
  var string = new TextDecoder("utf-8").decode(view);
  console.log("Chunk " + string);
  </code></pre>
  
  <p>but this may not read the last line as a whole, so how are you going to determine the lines later? For example here is what it printed:</p>
  
  <pre><code>((7202), (u'11330875493', u'2554375661'))
  ((1667), (u'9079074735', u'6883914476',
  </code></pre>