I continued the implementation of linux commands with the help of node.js. This time I’ve choosen the wc command. You can see the code below, it is a really small program. It does not have all the features which the original command has, it can do 3 basic things: counting the newlines, counting the words and counting the characters from a given file.

There is a method which I would like to explain more in depth: checkIfFileExists. Here it is used the statsync method of the node.js file system module. The statsync method returns information(stats) about a file; these can be queried with the help of the following methods:

The code of the checkFileExists method raises an error if there was no input passed to it, or the given path is not pointing to a file.

The countLines function logic is simple, it reads the content of the file, and splits the string read by the new line delimiter (under linux this is the “\n”).

The countWords function does almost the same thing as the countLines, the only difference is, after splitting the content of the file to lines with the new line delimiter, the lines’ content is also splitted using the ‘ ‘ [SPACE] character as splitting value. After having the content of the file splitted based on new lines and spaces, it is easy to sum up the number of words.

The countCharacters method is the most simple one, it reads the content of the file and returns the length of the string.

For splitting up and working with command line arguments I use a node js module called commander. This can be installed very easily with the classic npm install command.

I was testing the code with few files and it seems to work ok, it gives the same results as the original wc command. The implementation is not 100% yet, but I will try to improve it; or you can fork my github repo with these linux command clones from the linjs repository and add some features.

Thanks for reading…

0 Comments

Cancel Comment