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!


Playwright CLI Flags Tutorial

5 Playwright CLI Flags That Will Transform Your Testing Workflow

  • 0:56 --last-failed
  • 2:34 --only-changed
  • 4:27 --repeat-each
  • 5:15 --forbid-only
  • 5:51 --ui --headed --workers 1

Learn how these powerful command-line options can save you time, strengthen your test suite, and streamline your Playwright testing experience. Click on any timestamp above to jump directly to that section in the tutorial!

Watch Full Video ๐Ÿ“น๏ธ

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

๐Ÿ‘‹ Kindness is contagious

If you found this article helpful, a little โค๏ธ or a friendly comment would be much appreciated!

Got it