I’ve been working on a super-awesome-secret node.js project… and I had a need for a high-performance way to read how many lines a file has. Well, I’ve generalized my code a bit to count the number of occurrences of a substring in a larger string. Use the countInString function below to count how many occurrences of needle exist in haystack. This function should work on all standard JavaScript environments (including the browser!).
I’ve also provided my more specific function, which can be used on node.js to count the number of times an arbitrary string occurs in a file. I called the function countInFile. This function can easily be used to count the number of lines in a file, if you set the needle to the newline character \n.
The arguments for countInFile are as follows:
Argument: path is the path to the file you want to count the occurrences of the needle.
Argument: needle is the string you are looking for in the file.
Argument (optional): bufferSize is the size of the chunks you want the file to be read by.
Argument: callback function that will be called when the counting is done. The callback should have the following parameters: