Vue - Read large csv line-by-line
by Christopher O
HTML
<div id="app">
<input type="file" ref="myFile" @change="selectedFile">
</div>
CSS
body {
background: #20262E;
padding: 20px;
font-family: Helvetica;
}
#app {
background: #fff;
border-radius: 4px;
padding: 20px;
transition: all 0.2s;
}
li {
margin: 8px 0;
}
h2 {
font-weight: bold;
margin-bottom: 15px;
}
del {
color: rgba(0, 0, 0, 0.3);
}
Vue
new Vue({
el: "#app",
data: {
countLines: 0,
targetLines: 300,
},
methods: {
selectedFile() {
let self = this;
let file = self.$refs.myFile.files[0];
console.log('selected a file: '+file.name);
console.log(file);
let navigator = new FileNavigator(file);
let keepLines = [];
// Read exact amount of lines (start, limit, ...)
navigator.readLines(0, self.targetLines, function (err, index, lines, eof, progress) {
if (err) {
console.log('Error: ' + err);
return;
}
keepLines = keepLines.concat(lines);
self.countLines += lines.length;
console.log('Read ' + lines.length + ' lines');
if(self.countLines >= self.targetLines || eof) {
console.log('FINISHED. Total ' + self.countLines + ' lines readed');
console.log(keepLines);
return;
}
if(self.countLines < self.targetLines)
navigator.readSomeLines(index + lines.length, linesReadHandler);
});
// Read some amount of lines (best performance for sequential file reading)
//navigator.readSomeLines(0, function (err, index, lines, eof, progress) {
// Read exact amount of lines
//navigator.readLines(startingFromIndex, count, function (err, index, lines, eof, progress) { ... });
// Find first from index
//navigator.find(pattern, startingFromIndex, function (err, index, match) { ... });
// Find all matching lines
//navigator.findAll(new RegExp(pattern), indexToStartWith, limitOfMatches, function (err, index, limitHit, results) { ... });
}, // END selectedFile
}
});
// by Anton Purin, 2015 MIT https://github.com/anpur/client-line-navigator
function LineNavigator(e,t,n){function c(e,t){var n=e.exec(t);return!n?null:{offset:t.indexOf(n[0]),length:n[0].length,line:t}}var r=this;if(typeof...