Skip to content

Instantly share code, notes, and snippets.

@FGRibreau
Created July 18, 2012 12:29
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FGRibreau/3135914 to your computer and use it in GitHub Desktop.
Save FGRibreau/3135914 to your computer and use it in GitHub Desktop.
Find if a NodeJS module is available to require or not
node_modules
var mod = require('module');
module.exports = function module_exist(name){
/**
* This is UGLY but since we're not allowed to require 'native_module'
* this is the only way to test if a native module (or non-native module) exist.
*/
try{
require(name);
} catch(err){
if(err.code === 'MODULE_NOT_FOUND'){
return false;
}
}
return true;
};
{
"name": "node-module_exist",
"description": "Find if a NodeJS module is available to require or not",
"version": "0.0.1",
"main": "module_exist.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"repository": {
"type": "git",
"url": "git@gist.github.com:3135914.git"
},
"homepage": "https://github.com/FGRibreau",
"author": {
"name": "Francois-Guillaume Ribreau",
"url": "http://fgribreau.com.com/"
},
"devDependencies": {
"nodeunit": "~0.7.4"
},
"keywords": [
"core",
"modules"
],
"license": "MIT"
}
var exist = require('./');
module.exports.nativeModules = function(t){
t.expect(3);
t.equal(exist('fs'), true, "fs module exist");
t.equal(exist('module'), true, "module module exist");
t.equal(exist('redis'), false, "redis module doesn't exist");
t.done();
};
module.exports.notNativeModules = function(t){
t.expect(2);
t.equal(exist('nodeunit'), true, "nodeunit module exist");
t.equal(exist('this_is_gonna_be_legen____wait_for_it____dary'), false, "redis module doesn't exist");
t.done();
};
@jhermsmeier
Copy link

Can be also achieved by using require.resolve (which doesn't load the module):

function module_exists( name ) {
  try { return require.resolve( name ) }
  catch( e ) { return false }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment