DEV Community

Cover image for ๐ŸŒŸ Creating and Publishing a CLI Tool to Check NPM Package Stats ๐Ÿš€
Abhinav
Abhinav

Posted on

3 1 1

๐ŸŒŸ Creating and Publishing a CLI Tool to Check NPM Package Stats ๐Ÿš€

In the world of Node.js development, Command-Line Interface (CLI) tools are powerful utilities that help streamline workflows and automate repetitive tasks. In this blog, weโ€™ll walk through the process of creating, testing, and publishing a CLI tool that fetches ๐Ÿ“Š statistics about an NPM package.


๐Ÿ”ง What Weโ€™re Building

Weโ€™ll build a CLI tool called npm-stats-cli that allows users to retrieve details about any NPM package, such as its name, latest version, description, and homepage.


1๏ธโƒฃ Step 1: Setting Up the Project

First, initialize a new Node.js project:

mkdir npm-stats-cli
cd npm-stats-cli
npm init -y
Enter fullscreen mode Exit fullscreen mode

Install the dependencies weโ€™ll use:

npm install axios yargs
Enter fullscreen mode Exit fullscreen mode
  • axios: ๐ŸŒ For making HTTP requests to the NPM registry.
  • yargs: ๐Ÿ› ๏ธ For parsing command-line arguments.

2๏ธโƒฃ Step 2: Writing the CLI Tool

Create an index.js file for the CLI logic. Add the following code:

#!/usr/bin/env node

const axios = require('axios');
const yargs = require('yargs');

const getPackageStats = async (pkgName) => {
  try {
    const response = await axios.get(`https://registry.npmjs.org/${pkgName}`);
    const packageData = response.data;

    console.log(`\n๐Ÿ“ฆ Package Stats:`);
    console.log(`๐Ÿ”ค Name: ${packageData.name}`);
    console.log(`๐Ÿ†• Version: ${packageData['dist-tags'].latest}`);
    console.log(`๐Ÿ“ Description: ${packageData.description}`);
    console.log(`๐Ÿ•’ Last modified: ${packageData.time.modified}`);
    console.log(`๐Ÿ”— Homepage: ${packageData.homepage || 'No homepage available'}\n`);
  } catch (error) {
    console.error('โŒ Error fetching package data:', error.message);
  }
};

yargs.command({
  command: 'stats',
  describe: 'Get stats for an NPM package ๐Ÿ“Š',
  builder: {
    package: {
      describe: 'Package name',
      demandOption: true,
      type: 'string',
    },
  },
  handler: (argv) => {
    getPackageStats(argv.package);
  },
}).argv;
Enter fullscreen mode Exit fullscreen mode

3๏ธโƒฃ Step 3: Configuring for Global Use

Update your package.json to include a bin field:

"bin": {
  "npm-stats": "./index.js"
}
Enter fullscreen mode Exit fullscreen mode

This ensures that the npm-stats command is available globally when installed.

Link the tool locally for testing:

npm link
Enter fullscreen mode Exit fullscreen mode

Test the command:

npm-stats stats --package axios
Enter fullscreen mode Exit fullscreen mode

4๏ธโƒฃ Step 4: Publishing to NPM

To make your tool available globally, publish it to the NPM registry.

  1. Log in to your NPM account:
   npm login
Enter fullscreen mode Exit fullscreen mode
  1. Ensure the package name is unique. If itโ€™s taken, choose a different name or use a scoped name:
   "name": "@yourusername/npm-stats-cli"
Enter fullscreen mode Exit fullscreen mode
  1. Publish the package:
   npm publish
Enter fullscreen mode Exit fullscreen mode

๐ŸŒ Your tool is now available to the world!


๐Ÿšง Common Issues and Fixes

โŒ Error: E403 Forbidden

This error occurs if the package name is already taken. Rename the package in package.json and try again.

โŒ Error: EEXIST: file already exists

This happens if an existing file or symlink conflicts with your CLI command. Remove the conflicting file:

rm -f /path/to/conflicting/file
Enter fullscreen mode Exit fullscreen mode

Then reinstall your tool globally.


5๏ธโƒฃ Step 5: Enhancements

Here are a few ways to make your tool even better:

  • ๐Ÿ”’ Add Error Handling: Improve error messages for better user feedback.
  • ๐Ÿ“ˆ Include More Stats: Extend the tool to fetch download statistics or dependency lists.
  • ๐Ÿ“– Improve Documentation: Add a detailed README.md for users.

๐ŸŒŸ Conclusion

Building a CLI tool like npm-stats-cli not only improves your understanding of Node.js but also gives you an opportunity to contribute to the developer community. The process of testing, debugging, and publishing a global tool teaches valuable lessons about package management, versioning, and user experience.

๐Ÿ’ฌ Have you built your own CLI tool? Share your experience in the comments below!


Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

๐Ÿ‘‹ Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay