Build your own Javascript CLI in 90 seconds

dragosv99

Dragos Vecerdea

Posted on December 8, 2020

Build your own Javascript CLI in 90 seconds

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
Enter fullscreen mode Exit fullscreen mode

Step 1 - Initialize your project

npm init
Enter fullscreen mode Exit fullscreen mode

Step 2 - Create the entry point to your CLI

touch index.js && open ./index.js
Enter fullscreen mode Exit fullscreen mode

Step 3 - Add to index.js a shebang and the CLI's logic

#!/usr/bin/env node

console.log('hello world')
Enter fullscreen mode Exit fullscreen mode

Step 4 - Add index.js to project's executables

Add to package.json the following field:

"bin" :  {
  "myproject" : "./index.js"
},
Enter fullscreen mode Exit fullscreen mode

Step 5 - Symlink your project

npm link
Enter fullscreen mode Exit fullscreen mode

Step 6 - Your CLI should be now up and running!

In your Terminal, run:

myproject
Enter fullscreen mode Exit fullscreen mode

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

💖 💪 🙅 🚩
dragosv99
Dragos Vecerdea

Posted on December 8, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related