Search code examples
node.jsmodulerequire

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


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?


Solution

  • 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.