Javascript: how to parse a FileReader object line by line

I have a javascript / HTML5 page that I want to use to pull out a file and check each line to see if it exceeds 240 characters:

EDIT: I have things that understand correctly, but they do not display correctly. Here is my updated code:

<!DOCTYPE HTML> <html> <head> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"> <link href="https://netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet"> </head> <body> <input type="file" id="input" name="file" multiple /> <br> <output id="files"></output> <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script> <script> if (window.File && window.FileReader && window.FileList && window.Blob) { // Great success! All the File APIs are supported. } else { alert('The File APIs are not fully supported in this browser.'); } function handleFileSelect(evt) { var files = evt.target.files; // FileList object // files is a FileList of File objects. List some properties. var output = []; for (var i = 0, f; f = files[i]; i++) { var reader = new FileReader(); reader.onload = function(e) { // Print the contents of the file var text = e.target.result; var lines = text.split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks for(var i = 0; i < lines.length; i++) { if (lines[i].length > 240){ output.push('<li>' + lines[i] + '<br>'); } } }; reader.readAsText(f,"UTF-8"); } document.getElementById('files').innerHTML = 'Paths with more than 240 characters: <br><ul>' + output.join('') + '</ul>'; } document.getElementById('input').addEventListener('change', handleFileSelect, false); </script> </body> </html> 

I can run the trace and see that the output variable fills correctly, but all I get for the output is: Paths with more than 240 characters: without rendering the part of output.join() correctly - any thoughts?

+8
javascript html5
source share
2 answers

I think you should put

 document.getElementById('files').innerHTML = 'Paths with more than 240 characters: <br><ul>' + output.join('') + '</ul>'; 

inside onload callback. It seems that output is not output yet when you try to use it. So:

 reader.onload = function (e) { // all your code ... // now can safely print output document.getElementById('files').innerHTML = 'Paths with more than 240 characters: <br><ul>' + output.join('') + '</ul>'; }; 
+3
source share

The obvious way (if you can tolerate reading the entire file at the same time) is to split it into new lines.

 var lines = text.split(/[\r\n]+/g); // tolerate both Windows and Unix linebreaks for(var i = 0; i < lines.length; i++) { /* do something with lines[i] */ } // or in modern JavaScript, lines.forEach(function(line) { /* ... */ }); 
+3
source share

All Articles