NodeJS can be very useful when it comes to building Command-line Interfaces also known as CLI’s.
In this post, I’ll teach you how to build a CLI that asks some questions and creates a file, based on the answers.
Getting started
Let’s start by creating a brand new npm package
mkdir my-script
cd my-script
npm init
NPM will ask some questions. After that, we need to install some packages.
npm install --save chalk figlet inquirer shelljs
What these packages do:
- chalk — Terminal string styling done right
- figlet — Figlet is a program for making large letters out of ordinary text
- inquirer — A collection of common interactive command line user interfaces
- shelljs — Portable Unix shell commands for Node.js
index.js file
Now create a index.js
file with the following content:
Planning the CLI
it’s always good to plan what a CLI needs to do before writing any code.
This CLI will do just one thing: Create a file.
It should ask a couple of questions and after that, show a success message with the created file path.
The questions are: what is the filename and what is the extension.
The first function is the script introduction. Let’s use chalk
and figlet
to get the job done.
Now it’s time to write a function that asks questions.
Notice the constants FILENAME and EXTENSIONS that came from inquirer
.
The next step is to create the file.
And last but not least, show the success message along with the file path.
Let’s test the script by running node index.js
.
And here is the final code:
Using the script anywhere
To execute this script anywhere add a bin section in your package.json
file and run npm link
After running npm link
this script will be available anywhere.
That’s what happens when you run this command:
/usr/bin/creator -> /usr/lib/node_modules/creator/index.js
/usr/lib/node_modules/creator -> /home/hugo/code/creator
It links the index.js
file as an executable.
This is only possible because of the first line of the script: #!/usr/bin/env node
Now you can run this script by just calling:
$ creator
Hope it helps :)
✉️ Subscribe to CodeBurst’s once-weekly Email Blast, 🐦 Follow CodeBurst on Twitter, view 🗺️ The 2018 Web Developer Roadmap, and 🕸️ Learn Full Stack Web Development.