Testing Whether an NPM Module Is Installed

Node doesn’t have a well documented way of checking whether a module is available. This is usually fine. You just include a package.json in your project, and expect people to run npm install. This is how most popular Node frameworks work.

But what if you have a devDependency entry that you want to include only if it is installed? I searched for an answer and didn’t find anything conclusive, so I’m documenting what I did find in case I forget later.

Buried in NPM’s package.json documentation is an example for handling a package that may or may not be installed. In short, you use a try/catch. Here’s an example:

1
2
3
4
5
6
7
8
9
10
11
12
var program;

try {
    program = require('commander');
} catch (er) {
    // Any code to run if this module doesn't exist
}

if (program) {
    program.version('0.0.1') .option('-n, --name[name]', 'Your name')
         .parse(process.argv);
}
I am now accepting new clients for part-time consulting and software development projects. Learn more

I haven't configured comments for this blog, but if you want to get in touch, you can find me on Twitter