Node.js can be very useful when it comes to building command-line interfaces (CLIs). In this post, I'll teach you how to use [Node.js][1] to build a CLI that asks some questions and creates a file based on the answers.
### Get started
Let's start by creating a brand new [npm][2] package. (Npm is the JavaScript package manager.)
```
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
```
Here's what these packages do:
* **Chalk:** Terminal string styling done right
* **Figlet:** 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
### Make an index.js file
Now we'll create an `index.js` file with the following content:
```
#!/usr/bin/env node
const inquirer = require("inquirer");
const chalk = require("chalk");
const figlet = require("figlet");
const shell = require("shelljs");
```
### Plan 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**.
The CLI will ask two questions—what is the filename and what is the extension?—then create the file, and show a success message with the created file path.
```
// index.js
const run = async () => {
// show script introduction
// ask questions
// create the file
// show success message
};
run();
```
The first function is the script introduction. Let's use `chalk` and `figlet` to get the job done.
```
const init = () => {
console.log(
chalk.green(
figlet.textSync("Node JS CLI", {
font: "Ghost",
horizontalLayout: "default",
verticalLayout: "default"
})
)
);
}
const run = async () => {
// show script introduction
init();
// ask questions
// create the file
// show success message
};
run();
```
Second, we'll write a function that asks the questions.
```
const askQuestions = () => {
const questions = [
{
name: "FILENAME",
type: "input",
message: "What is the name of the file without extension?"
},
{
type: "list",
name: "EXTENSION",
message: "What is the file extension?",
choices: [".rb", ".js", ".php", ".css"],
filter: function(val) {
return val.split(".")[1];
}
}
];
return inquirer.prompt(questions);
};
// ...
const run = async () => {
// show script introduction
init();
// ask questions
const answers = await askQuestions();
const { FILENAME, EXTENSION } = answers;
// create the file
// show success message
};
```
Notice the constants FILENAME and EXTENSIONS that came from `inquirer`.