Wednesday, June 5, 2024
20
rated 0 times [  21] [ 1]  / answers: 1 / hits: 16854  / 7 Years ago, fri, august 11, 2017, 12:00:00

I'm developing this code that, after the user selects a directory, it display a table of the files contained in that location with their details (name, type, size ...).



A directory may contain a lot of files.



I succeeded to achieve that. But, my problem is that I want to display the number of lines in each file. I can get the number of lines using this JavaScript code :



var reader = new FileReader();
var textFile = $(#file).get(0).files[0];
reader.readAsText(textFile);
$(reader).on('load', processFile);
/*And in processFile() i use this line to get the number of lines :*/
nbLines = (file.split(n)).length;


The above code work as expected and it give me what I want, but it may a heavy process if there is so many files in the selected directory!



The Question : Is there a way to get the number of lines in a text file without reading it?



Regards!


More From » optimization

 Answers
4

You can't count the number of lines in a file without reading it. The operating systems your code runs on do not store the number of lines as some kind of metadata. They don't even generally distinguish between binary and text files! You just have to read the file and count the newlines.



However, you can probably do this faster than you are doing it now, if your files have a large number of lines.



This line of code is what I'm worried about:



nbLines = (file.split(n)).length;


Calling split here creates a large number of memory allocations, one for each line in the file.



My hunch is that it would be faster to count the newlines directly in a for loop:



function lineCount( text ) {
var nLines = 0;
for( var i = 0, n = text.length; i < n; ++i ) {
if( text[i] === 'n' ) {
++nLines;
}
}
return nLines;
}


This counts the newline characters without any memory allocations, and most JavaScript engines should do a good job of optimizing this code.



You may also want to adjust the final count slightly depending on whether the file ends with a newline or not, according to how you want to interpret that. But don't do that inside the loop, do it afterward.


[#56801] Tuesday, August 8, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
michelecarissab

Total Points: 730
Total Questions: 97
Total Answers: 110

Location: Uzbekistan
Member since Sat, Feb 27, 2021
3 Years ago
;