Skip to content

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.

The count-word command reads a file and returns the exact number of words inside it.

Terminal window
somethingzz count-word <filepath>

Example:

Terminal window
somethingzz count-word package.json

Output in terminal:

Terminal window
found 25 words in this file.

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!


Similar to counting words, the count-lines command returns the number of lines in a file.

Terminal window
somethingzz count-lines <filepath>

Example:

Terminal window
somethingzz count-lines src/index.ts

Output in terminal:

Terminal window
found 132 lines in this file.

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!