Unlock the Power of Command-Line Interfaces
When it comes to developer tools and quick projects, a command-line interface (CLI) can be a game-changer. In fact, sometimes a CLI provides a better experience than a graphical user interface (GUI). In this article, we’ll explore how to create a Node CLI to check sports news using data from ESPN.com.
Setting Up the Project
To get started, create a new directory, initialize an npm package, and create an index.js
file where we’ll write all our code. Then, install the necessary packages and mark our package as a module by adding a line to our package.json
file.
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. To indicate to the user that the CLI is loading, we’ll use a library called ora to show an animated loading indicator.
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, and 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.
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. We’ll create our first prompt to show the user which story from the homepage they’d like to read, then give them a few options.
Handling User Selections
We’ll handle each type of selection differently. If the user chooses to exit, we’ll quit the CLI. If they choose a specific sport, we’ll show headlines for that sport. If they choose an article, we’ll show the 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. We’ll use a node-localstorage module to store a count of daily executions and Chalk to change the log color.
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!