How to make your CLI projects outstanding with node.js

How to make your CLI projects outstanding with node.js

The one thing that makes developers different from the common people out there is the command line. Today we are taking things to the next level with the help of node.js, so make sure it’s installed on your machine if not then go here

To get an idea of what one can pull off with this article, run the following command in your terminal.

npx flexquiz

One can also upload personal packages on npm which I will cover at the end of this article.

Now, let’s get started:

  1. Create a directory for our sample tool:
mkdir sample-tool

cd sample-tool
  1. Open this directory in your code editor and run:
npm init -y

This will create package.json file which will be helpful for installing dependencies.

  1. Now, install the packages we need; by running this command:
npm i chalk chalk-animation figlet gradient-string inquirer nanospinner
  1. Add “type” in package.json and set it to “module”.
"type": "module",
  1. Then, create an index.js file and add this ‘shebang’ at the top:
#!/usr/bin/env node

Always include a ‘shebang’ when you want others to use your command line script.

  1. Now let’s import all the packages we want to use in our project:
import chalk from 'chalk';
import inquirer from 'inquirer';
import gradient from 'gradient-string';
import chalkAnimation from 'chalk-animation';
import figlet from 'figlet';
import { createSpinner } from 'nanospinner';

Chalk: This package will help us print coloured output messages on the terminal.

inquirer: An interactive command line tool for collecting user input.

gradient: It is like chalk but provides gradient-styled output messages in the terminal.

Chalk-animation: Most useful package in the list, it’s built on top of chalk and is used to animate the output messages on the terminal.

figlet: Used to print output messages in the form of ASCII art in the terminal.

nano-spinner: The smallest and tiniest spinner for node.js.

  1. As we are using animations in our terminal so we need to wait for them so that users can see them. For that purpose, we need to define a constant variable sleep:
const sleep = (ms = 2000) => new Promise((r) => setTimeout(r, ms));
  1. Now, let’s use ‘chalk-animation’ and ‘chalk’ for defining a welcome function:
async function welome(){
    const rainbowTitle = chalkAnimation.rainbow('Welcome to our CLI quiz!...\n');

    await sleep();

    rainbowTitle.stop();

    console.log(`${chalk.blueBright('Answer all the questions correctly :)')}`);
    await sleep();
}
  1. To check, run (in terminal):
node .

(Make sure you are in the sample-tool directory)

NOTE: - Make sure to wait for every function after defining it like for welcome:

await welcome();

The output should be like this:

image.png

  1. Let’s prompt user to enter their name with ‘inquirer’ package:
let playerName;

async function askName(){
    const answers = await inquirer.prompt({
        name: 'player_name',
        type: "input",
        message: "Enter your name.",

    });

    playerName = answers.player_name;
}

Run “node .” in terminal and it should look like this:

image.png

  1. Now let’s prepare a multiple-choice question with ‘inquirer’:
async function question1(){
    const answers = await inquirer.prompt({
        name: 'question_1',
        type: 'list',
        message: 'How many sides does square have?',
        choices: [
            '1',
            '2',
            '3',
            '4',
        ],
    });

    return handleAnswer(answers.question_1 === '4');
}

Notice that we called the function ‘handleAnswer()’ for checking if the answer is right or wrong.

  1. We are using ‘nano-spinner’ for ‘handleAnswer()’ function:
function winner(){
    console.clear();
    const msg = `Well done ${playerName}! You are winner!`;

    figlet(msg, (err, data) => {
        console.log(gradient.pastel.multiline(data));
    });
}
await winner();
async function handleAnswer(isCorrect){
    const spinner = createSpinner('Checking....').start();
    await sleep();

    if (isCorrect){
        spinner.success({text: `Great ${playerName}. it's a correct answer!`});
    }
    else{
        spinner.error({text:'Wrong answer you lose...'});
        await sleep();
        await sleep();
        process.exit(1);
    }
}

The question should look like this:

image.png

  1. Finally let’s look at the winning animation with ‘figlet’ and ‘gradient’:
function winner(){
    console.clear();
    const msg = `Well done ${playerName}! You are winner!`;

    figlet(msg, (err, data) => {
        console.log(gradient.pastel.multiline(data));
    });
}
await winner();

the winning animation should look like this:

image.png

  1. As I promised, let’s upload our package on npm as executable so that others can also use it.

  2. First, go to package.json and add:

"bin": "./index.js",
  • Then, you need an npm account, so make one if you don’t have then run:
npm login
  • Login with your username and password then run:
npm publish

Congratulations you just published your CLI tool to npm and others can also use it by running:

npx <name of your tool>

#BlogsWithCC

Did you find this article valuable?

Support WeMakeDevs by becoming a sponsor. Any amount is appreciated!