Write your own CLI tool using Node.js
I originally wrote about how to write a command line utility in Node.js back in 2013 when I was first learning how to do it myself. In the three years that have past the Node.js ecosystem has continued to grow so I thought it was about time to update my original post. If you want to see the original post it is still online over here.
Before we can build our command line interface we will need to install both Node.js and NPM on your computer. Instructions to installing these can be found over at How To Node https://howtonode.org/how-to-install-nodejs.
Having ensured we have the pre-requisites installed we now need to open the terminal in the directory we want to initialise our project. We will then run
Having run this command we will then be asked a series of questions about our project by NPM, for this project we are going to name our command line tool hello. Below are the answers I used for the questions it asked (the answers in brackets are the default answers which I hit enter to accept).
description: Simple hello world CLI
entry point: (index.js) hello.js
author: Jonathan Fielding
license: (ISC) MIT
We will then be prompted with the JSON that NPM has generated:
"description": "Simple hello world CLI",
"test": "echo \"Error: no test specified\" && exit 1"
"author": "Jonathan Fielding",
To accept this simply hit enter.
At this point all we have in our directory is the package.json file generated by NPM init, so we will now create the JS file used by our command line. As we specified above we will create a file called hello.js in the root of our project. The aim of our JS script is to simply log ‘hello world’ to the command line when our hello cli tool is run. To achieve this the first thing we need to do is tell our script how it should be executed, to configure this for Node.js the first line of our script should be:
#! /usr/bin/env node
Having done this we can now write the rest of our script, as we just want to say hello world on the command line the full script is as follows.
#! /usr/bin/env node
"hello" : "hello.js"
We have told our package.json that whenever the user of our utility enters ‘hello’ on their cli, it should run hello.js. We now simply need to return to our console and run npm link which will install the CLI tool on our machine. Once run test our running the hello command and you will see ‘hello world’ logged to the console.