One of the most common things we Software Engineers do is tinker with code. That is what I have done with Javascript and NodeJS.
I created a CLI tool that uses a custom npm package to display a nerdy style business card. Here is how I created it:
Using javascript for CLIs is easy
- the npm build, publish, and share cycle is so easy
npx
allows you to execute without installation- the npm ecosystem is ripe for CLIs
npx business card
We will be using the command line to during part of this tutorial.
Let’s start creating this business card. The final output might look something like this: (I have customized this quite a bit to my needs)
npm init
First, let’s start off by creating a new node
project and name it whatever you want. I would suggest naming it after the exectuable you want to expose. You don’t have to but naming conventions are good and it makes it more npx
friendly.
mkdir kylereddoch
cd kylereddoch
npm init -y
Now, let’s get the neccessary CLI working. I named mine card.js but you can name yours whatever you want.
touch card.js
chmod +x card.js
Now that the file is created, open the file in your favorite editor. I am partial to vs code
but you can use any editor you want.
Once you open the file, it will be blank. Let’s add some test
code.
#!/usr/bin/env node
console.log('doing business')
Now within the same folder you created, you can execute the file like this:
./card.js
ship it
You know have a functional first release of your CLI tool. Now, let’s ship it.
If you do not already have a npm account you can create one either online at npmjs.com or by using cli as follows and following the directions:
npm adduser
Once you have created a user, you can login to npm by using the following command:
npm login
Once you are logged in, you can publish your CLI to the world!
npm publish
Once you have published your CLI, anyone can install it globally by using the following command:
npx kylereddoch
making updates
Now that you have published your CLI, you can make updates to it and publish them. You can also update the version number in your package.json
file and publish it as a new version.
If you want to update the version number using the command line, you can do so by using the following commands:
To update the version number to a major release:
npm version major
To update the version number to a minor release:
npm version minor
Or to update the version number to a patch release:
npm version patch
Once you have updated the version number, you can publish it to npm by using the following command:
npm publish
Conclusion
I hope you enjoyed this tutorial. You can find the raw code for this tutorial on GitHub. If you have any questions, please feel free to reach out to me on Twitter or via Email.