Check if a node.js module is available

There is a more clever way if you only want to check whether a module is available (but not load it if it’s not):

function moduleAvailable(name) {
    try {
        require.resolve(name);
        return true;
    } catch(e){}
    return false;
}

if (moduleAvailable('mongodb')) {
    // yeah we've got it!
}

Leave a Comment