Building a Node JS interactive CLI
source link: https://www.tuicool.com/articles/hit/7jAFBb3
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Building a Node JS interactive CLI
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:
To execute this script anywhere add a bin section in your package.json
file and run npm link
$ npm link $ creator
Hope it helps :)
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK