public
Created

Find if a NodeJS module is available to require or not

  • Download Gist
.gitignore
1
node_modules
module_exist.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
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;
};
package.json
JSON
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
{
"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"
}
test.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
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();
};

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 }
}

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.