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!
}
Here is the most clever way I found to do this. If anyone has a better way to do so, please point it out.
var mongodb;
try {
mongodb = require( 'mongodb' );
}
catch( e ) {
if ( e.code === 'MODULE_NOT_FOUND' ) {
// The module hasn't been found
}
}