JS

DIY Node CLI

John Sylvain - April 13, 2019

I recently created a CLI tool with Node and was surprise how it easy it was to get it up and running. Here are the steps I took for getting started.

Initializing the NPM package

You've likely done this before. Run the npm init command and accept the defaults.

The most important thing to do in the newly created package.json is to specify the location of the binary that you want to be executed. This is done by adding the following to package.json:

"bin": {
  "<name of the cli command>": "bin/cli.js"
}

You can define the command that you want the user to type to execute your tool as the key, and the path to the script as the value.

Shebang

In order for our CLI script to be executed we need to include a Node shebang at the top of our .js file. I also like to include 'use strict' to enable strict mode.

#!/usr/bin/env node
'use strict';

// Your Node script here

The shebang is read by the operating system's program loader and passes the following script to the executable mentioned.

Make it easy with Meow

Meow is a great helper package for creating CLI tools. You just define the help/usage text and expected flags/arguments and Meow takes care of the rest.

Publishing

If you've never published an NPM package, make sure you create an account on npmjs.org first.

Log in with your credentials via npm login. When your ready to publish your package, run npm publish.

An example

I recently created a CLI tool to print all College Basketball live scores and game times in the terminal (found here). Using the steps I mentioned above I was able to get it up and running in less than an hour. Pretty nice!