DEV Community

Dragos Vecerdea
Dragos Vecerdea

Posted on

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

Top comments (3)

Collapse
 
braydentw profile image
Brayden W ⚡️

Thanks for the great tip! Do you think that starting off with these steps could eventually end up with a super cool open source CLI?

Collapse
 
dragosv99 profile image
Dragos Vecerdea • Edited

Great to hear about your interest in the topic! Starting off with these steps can really be the base for a cool open source CLI. Indeed, there are plenty of steps that should follow, but it can serve as a great base as you can already run it.

These are the steps I also use in my own projects. If interested, you can check my latest open course CLI here. Feel free to fork the project and use it as a template.

Collapse
 
braydentw profile image
Brayden W ⚡️

Thanks! I’ll check it out.