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:
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.
const run =