Safely detect if a Node.js module is installed before using require() to load it

nodejs-dark.pngSometimes you need to detect whether a Node.js module is installed, and print a useful error message if it isn't. For example Grunt does this. The instructions are to install "grunt-cli" then add "grunt" to the package.json for the project for which you want to use Grunt. If you haven't installed grunt locally, typing "grunt" gives you a nice error message telling you what to do. It does that instead of printing an ugly message from the "require" function saying your module wasn't loaded.

Click here for more Node.js programming advice

Grunt, in turn, requires that all modules used in a particular build are installed locally. That means if you're developing a tool for use with Grunt, where you want both a command line tool and some business logic to be called from the Gruntfile, that your users must also install two modules for your tool. One is a CLI module providing the command line tool, and the other is installed locally to provide the business logic.

In my case, the tool I've developed is AkashaCMS, a static website generator. It currently has a command line script that turns into the global command "akashacms", and the module itself is installed with "npm install -g akashacms" to put it in the global context. But using AkashaCMS with Grunt means installing the "akashacms" module in the local context. That means I need to change AkashaCMS so users "npm install -g akashacms-cli" then list "akashacms" in the package.json dependencies in their website.

The required pattern is this split:

  • CLI Module: A simple shell in global context
  • Local Module: The rest of your tool installed as a local module - e.g. a module with a package.json listing your module in the "dependencies" or "devDependencies"

Turns out to be very easy.

We start by making a new module named something like "xyzzy-cli" (I named it "akashacms-cli" - or https://github.com/akashacms/akashacms-cli)

It requires three or maybe four files, at a minimum:

  • package.json
  • cli.js
  • README.md
  • LICENSE

In the package.json there's a critical entry:

  "bin": {
    "xyzzy": "cli.js"
  }

Substitute your preferred command name for "xyzzy".

The README.md should of course say how great your tool is, and link to its homepage. The LICENSE file should have whatever license statement you want to make.

In the package.json list this dependency

  "dependencies": {
    ...
    "resolve": "*"
   ...
  }

You might well have other dependencies, but list at least this one. Do not list the module containing your business logic because that module must be installed locally to your users project.

The next critical piece is the content of cli.js. The exact content for your cli.js is up to you, but there is a critical step required in order to locate the module with your business logic.

That step is made possible by the resolve module (https://github.com/substack/node-resolve). It is an implementation of Node.js's algorithm behind the "require" function. It's necessary to let us do this:

var fnxyzzy;
try {
    fnxyzzy = resolve('xyzzy', { basedir: process.cwd() });
} catch (ex) {
    console.error("Could not find XYZZY because: "+ ex);
    process.exit();
}
var xyzzy = require(fnxyzzy);

What this does is search for your module (again - substitute the name of your module for "xyzzy") from the current directory. This will find your module if it's been installed locally. For example if your current directory has a package.json listing "xyzzy" causing your module to have been installed in the local "node_modules" directory.

The console.error line should print out a nice message telling the person how to proceed to get started. For example this is what Grunt shows:

$ grunt
grunt-cli: The grunt command line interface. (v0.1.13)

Fatal error: Unable to find local grunt.

If you're seeing this message, either a Gruntfile wasn't found or grunt
hasn't been installed locally to your project. For more information about
installing and configuring grunt, please see the Getting Started guide:

http://gruntjs.com/getting-started

Your CLI module should then go ahead and do its business parsing command line options and performing the requested operation.