In this post you will make a NodeJS command line calculator and publish it to NPM all in just 10 minutes. So without any further ado lets start
Step 1 - Setup
- Name and create a project folder
mkdir <insert project name>
cd <insert project name>
- Initialize NPM
npm init -y
This command will create a package.json
file this file will contain all the details of our package
- Create a file called
cli.js
in the root of our project this is the file in which we will write code - Open the
cli.js
file and add this on the first line
#!/usr/bin/env node
This line will let our code know where to find NodeJS command
- Open the
package.json
file and at the very bottom add this line
"bin": "cli.js"
This line will let NPM know which file contains the code to execute when called
Step 2 - Code
Open up the cli.js
file and add the following code
let args = process.argv.slice(2);
console.log(eval(args[0]));
Now your cli.js
file should look like this
#!/usr/bin/env node
let args = process.argv.slice(2);
console.log(eval(args[0]));
Now let me explain the code line by line
-
#!/usr/bin/env node
This line will let our code know where to find NodeJS command -
let args = process.argv.slice(2);
this line will get the command line arguments given to the command line -
console.log(eval(args[0]));
Now this line will get the first argument and evaluate it and then print it out on the console.
Step 3 - Testing it out locally
First run
npm link
This will simulate a global install
Now open up yourpackage.json
and see the"name"
value and run like this
(Your package name in the package.json) 1+1
Now after testing it out run
npm unlink
Step 4 - Publishing!
Now before publishing to NPM you project needs to have a git repository so for that run this
git init .
git add .
git commit -m "My awesome CLI is ready"
and after you have initialized a git repository you will need a NPM account for that sign up here after signing up run this
npm login
after you enter your credentials you will be logged in
and finally run
npm publish
Now your command line tool is ready! Congratulation 🎉
Finishing up
If you are interested in seeing the whole code check them out on my GitHub
https://github.com/aadityasivaS/node-calc-cli
and the package is also on NPM
https://www.npmjs.com/package/@aadityasiva/n-c-c
Spoiler: Yes I saved it for last it may or may not take more than 10 minutes. It took me 5 minutes to do all the steps
Bye 👋 and good day
Top comments (4)
Nice! I find making Node CLIs to be a good way of keeping things cross-platform friendly while still providing the flexibility of the command line.
For more complex projects, I use Commander.js which does a lot of the boilerplate stuff (like parsing arguments and flags) for you.
It allows you to write quite neat code like:
Thanks for sharing really appreciate it
This is awesome !
Thanks