Unlock the Power of Command-Line Interfaces
Setting Up the Project
To get started, create a new directory and initialize an npm package:
mkdir sports-cli && cd sports-cli
npm init -y
Create an index.js
file where we’ll write all our code:
touch index.js
Install the necessary packages and mark our package as a module by adding a line to our package.json
file:
"type": "module"
Getting Display Data
Next, let’s add some functionality to our CLI. We’ll import a library for getting ESPN headlines and make an initial call to get them:
import axios from 'axios';
const getHeadlines = async () => {
const response = await axios.get('undefined.com/espn-headlines');
return response.data;
};
To indicate to the user that the CLI is loading, we’ll use a library called ora to show an animated loading indicator:
import ora from 'ora';
const spinner = ora('Loading headlines...').start();
const headlines = await getHeadlines();
spinner.stop();
Declaring CLI Options
In our CLI, we’ll give users a few different option types to choose from:
- An article to read
- A specific sport to see headlines for
- A MORE type to see more headlines for a specific sport
We’ll declare variables to handle user input differently based on the selection type:
let article;
let sport;
let more;
Creating Prompts with Enquirer
We’ll use Enquirer, a library that allows us to show something in the console and then await the user’s input:
import { prompt } from 'enquirer';
const homepagePrompt = {
type: 'elect',
name: 'tory',
message: 'Which story from the homepage would you like to read?',
choices: headlines.map((headline) => headline.title),
};
const response = await prompt(homepagePrompt);
Handling User Selections
We’ll handle each type of selection differently:
if (response.story === 'exit') {
process.exit(0);
} else if (response.story === 'port') {
// show headlines for that sport
} else if (response.story === 'article') {
// show article text with some styling using boxen
}
Adding Finishing Touches
Finally, we’ll add a log at the very start telling users how many times they’ve used the CLI in a day:
import chalk from 'chalk';
import localStorage from 'node-localstorage';
const executions = localStorage.getItem('executions') || 0;
console.log(chalk.cyan(`You've used this CLI ${executions} times today.`));
localStorage.setItem('executions', executions + 1);
Reviewing the Final Product
Our CLI is now complete! It shows ESPN homepage headlines, lists available sports, and lets us read articles. We’ve provided prompts for the user, displayed an animated spinner during loading, colored console output, and drawn boxes around some console text.
Taking It Further
Command-line interfaces can be incredibly helpful for productivity and can be a lot of fun to play around with. Explore and experiment with different Node CLI utilities to create something that’s helpful for you!