Search code examples
node.jsnpmcommand-line-interfacenpm-installversioning

How to notify NPM package version update to user?


I have written a CLI tool in Node JS and published to NPM. Every time it's run in terminal, I need the user to be notified of a new version available and its type (patch | minor | major) so that he/she can update it accordingly. How can I implement this?

Moreover, is it possible to ask the user if he/she would like to have the package updated by itself?

A new version of Rapid React is available. Would you like to update it now?(Y\n)

Solution

  • Version Update Check:

    I would suggest using update-notifier but strangely it doesn't work. So, I chose to handle this work by myself.

    The latest version can be checked easily with package-json which fetches the metadata of a package from the npm registry. Alternatively latest-version can be used as well which uses package-json under the hood.

    import boxen from 'boxen';
    import chalk from 'chalk';
    import semver from 'semver';
    import pkgJson from 'package-json';
    import semverDiff from 'semver-diff';
    
    import { capitalizeFirstLetter } from '../utils';
    
    import { name, version } from '../../package.json';
    
    const checkUpdate = async () => {
      const { version: latestVersion } = await pkgJson(name);
    
      // check if local package version is less than the remote version
      const updateAvailable = semver.lt(version, latestVersion as string);
    
      if (updateAvailable) {
        let updateType = '';
    
        // check the type of version difference which is usually patch, minor, major etc.
        let verDiff = semverDiff(version, latestVersion as string);
    
        if (verDiff) {
          updateType = capitalizeFirstLetter(verDiff);
        }
    
        const msg = {
          updateAvailable: `${updateType} update available ${chalk.dim(version)} → ${chalk.green(latestVersion)}`,
          runUpdate: `Run ${chalk.cyan(`npm i -g ${name}`)} to update`,
        };
    
        // notify the user about the available udpate
        console.log(boxen(`${msg.updateAvailable}\n${msg.runUpdate}`, {
          margin: 1,
          padding: 1,
          align: 'center',
        }));
      }
    };
    

    Update notification:

    Every time the tool runs, user would see such a notification if an update is available.

    enter image description here