DEV Community

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

Posted on

2

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


SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

πŸ‘‹ Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

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

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay