How to get the number of lines in a text file without opening it?

Viewed 14415

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!

4 Answers

Update for 2021:

Reading the file as text is always a bad idea. With current optimised languages, almost all languages are super fast in processing loops, so looping will always be faster than loading the text into memory and splitting.

for NodeJS, please see ReadLine. Although not recommended to do such operations in node, being Single Threaded, I can read Big CSVs pretty fast using ReadLine.

A text file usually contains an operation line at the bottom of the screen which allows you to place the cursor on the screen and shows the line and location of the character it is located. In which case if the cursor is at the last character the total lines would be indicated.

Related