The smallest file I have has > 850k lines and every line is of unknown length. The goal is to read n
lines from this file in the browser. Reading it fully is not going to happen.
Here is the HTML <input type="file" name="file" id="file">
and the JS I have:
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 < n; line++) {
console.log(lines[line]);
}
};
Obviously, the problem here is that it tries to first real the whole file and then split it by newline. So no matter of n
, it will try to read the whole file, and eventually read nothing when the file is big.
How should I do it?
Note: I am willing to delete the whole function and start from scratch, given that I will be able to console.log()
every line that we read.
*"every line is of unknown length" -> means that the file is something like this:
(0, (1, 2))
(1, (4, 5, 6))
(2, (7))
(3, (8))
Edit:
The way to go would be something like filereader api on big files, but I can't see how I can modify that to read n
lines of the file...
By using Uint8Array to string in Javascript too, one can do from there:
var view = new Uint8Array(fr.result);
var string = new TextDecoder("utf-8").decode(view);
console.log("Chunk " + string);
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:
((7202), (u'11330875493', u'2554375661'))
((1667), (u'9079074735', u'6883914476',