Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Javascript to read local text file and read line by line?

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.

like image 488
litaoshen Avatar asked Apr 28 '14 02:04

litaoshen


People also ask

How do I read a text file line by line in JavaScript?

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.

How do I read a .TXT file in JavaScript?

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.

Does JavaScript read line by line?

JavaScript is actually interpreted line by line.

Can JavaScript read local files?

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.


2 Answers

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.

like image 200
sites Avatar answered Oct 20 '22 13:10

sites


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); } 
like image 24
JuJoDi Avatar answered Oct 20 '22 13:10

JuJoDi