DEV Community

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

Posted on

🌟 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!


Top comments (0)