File Analysis Commands
The first phase of our CLI journey involves building file analysis tools. We wanted simple commands that could instantly tell us the size of a text file, beautifully formatted in the terminal.
Count Words
Section titled “Count Words”The count-word command reads a file and returns the exact number of words inside it.
somethingzz count-word <filepath>Example:
somethingzz count-word package.jsonOutput in terminal:
found 25 words in this file.How it Works
Section titled “How it Works”Under the hood, we use Node’s fs (File System) module to read the file synchronously. Then, we use a Regular Expression split(/\s+/) to split the entire text by spaces and newlines, giving us an array of words!
Count Lines
Section titled “Count Lines”Similar to counting words, the count-lines command returns the number of lines in a file.
somethingzz count-lines <filepath>Example:
somethingzz count-lines src/index.tsOutput in terminal:
found 132 lines in this file.How it Works
Section titled “How it Works”The logic is almost identical to counting words, except instead of splitting by whitespace, we split the text specifically by the newline character \n. The length of the resulting array is exactly the number of lines!