Node.js - check if module is installed without actually requiring it

AndreyM picture AndreyM · Mar 8, 2013 · Viewed 45.1k times · Source

I need to check whether "mocha" is installed, before running it. I came up with the following code:

try {
    var mocha = require("mocha");
} catch(e) {
    console.error(e.message);
    console.error("Mocha is probably not found. Try running `npm install mocha`.");
    process.exit(e.code);
}

I dont like the idea to catch an exception. Is there a better way?

Answer

user568109 picture user568109 · Mar 8, 2013

You should use require.resolve() instead of require(). require will load the library if found, but require.resolve() will not, it will return the file name of the module.

See the documentation for require.resolve

try {
    console.log(require.resolve("mocha"));
} catch(e) {
    console.error("Mocha is not found");
    process.exit(e.code);
}

require.resolve() does throw error if module is not found so you have to handle it.