To make a CLI tool with node.js I would start by making a new folder in a pace where I get projects done such as the home folder, or my documents folder what have you. At which point I would make it the current working directory, and set up a new node project by calling npm init to make my package.json file.
One of the most important steps to making a script global is setting the name that is to be called from the command line, and the script to be called when doing so. This is done by adding a bin entry to package.json file of my project.
So insert this anywhere into the package.json file.
This means that I will be calling my tool like this
and a file called index.js is what will be called when doing so.
So while still in the working directory of the project I just need to use npm to install the project globally by calling npm install and making sure to use the global flag like so:
Now I can cd to any path in my CLI and call cli-tool to get ‘hello-CLI!’ logged to the console, pretty sweet hua? Of course in order to start doing some things more interesting it is going to take more than just that, but this is the depth of this post.
I will not get into detail with it here, but I have written a post on a dependency that I use to help with option parsing called nopt. If you want to go vanilla process.argv is what is of interest when it comes to doing something involving arguments accepted from the CLI.
For this I have found chalk be sure to check that out if you want to do anything with color in the console.
I have wrote a post on an npm package called node-dir. It allows for working with the content of a bunch of files that are placed in a complex file structurer. I can set a match pattern using regular expressions, and I find it more useful then just using readDir in the fs module of node itself.
maybe I will make some more examples that do something a bit more interesting. For now I guess I will just reference some posts that I have written before that are relevant to this sort of thing. Of course I have many posts on node.js that are worth checking out.