Build your own Javascript CLI in 90 seconds
Dragos Vecerdea
Posted on December 8, 2020
Writing your own CLI (command line interface) can be really great as it allows you to automate any task you may want to and run it right from your Terminal.
Wait no more and get started with your first CLI:
Step 0 - Create your project directory
mkdir myproject && cd myproject
Step 1 - Initialize your project
npm init
Step 2 - Create the entry point to your CLI
touch index.js && open ./index.js
Step 3 - Add to index.js a shebang and the CLI's logic
#!/usr/bin/env node
console.log('hello world')
Step 4 - Add index.js to project's executables
Add to package.json the following field:
"bin" : {
"myproject" : "./index.js"
},
Step 5 - Symlink your project
npm link
Step 6 - Your CLI should be now up and running!
In your Terminal, run:
myproject
I hope you had fun, and since this is your first encounter with a CLI, that you are still excited and eager for more.
As said before, automating your own tasks using command-line scripts can be a great way to try new skills and experiment with new node modules. So far, we have just programmed a simple script but this skill can enable the use of more sophisticated ones.
Stay tuned for the next post, when we explore more complex options for creating a great CLI. Until next, I recommend you to check this great node module
Posted on December 8, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.