I have a web page made by html+javascript which is demo, I want to know how to read a local csv file and read line by line so that I can extract data from the csv file.
We can use the Node. js line-reader module to read the file in JavaScript. The module is open source, and we need to install it with the commands npm install line-reader --save or yarn add line-reader . Reading the content of a file using the line-reader module is easy as it provides the eachLine() method.
Use the fs. readFileSync() method to read a text file into an array in JavaScript, e.g. const contents = readFileSync(filename, 'utf-8'). split('\n') . The method will return the contents of the file, which we can split on each newline character to get an array of strings.
JavaScript is actually interpreted line by line.
JavaScript does not have direct access to the local files due to security and privacy. By using a file input and a File reader, you can read one or multiple local files. We can offer the user the possibility to select files via a “file input” element that we can then process.
Without jQuery:
document.getElementById('file').onchange = function(){ var file = this.files[0]; 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 < lines.length; line++){ console.log(lines[line]); } }; reader.readAsText(file); };
HTML:
<input type="file" name="file" id="file">
Remember to put your javascript code after the file field is rendered.
Using ES6 the javascript becomes a little cleaner
handleFiles(input) { const file = input.target.files[0]; const reader = new FileReader(); reader.onload = (event) => { const file = event.target.result; const allLines = file.split(/\r\n|\n/); // Reading line by line allLines.forEach((line) => { console.log(line); }); }; reader.onerror = (event) => { alert(event.target.error.name); }; reader.readAsText(file); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With