Created
July 18, 2012 12:29
-
-
Save FGRibreau/3135914 to your computer and use it in GitHub Desktop.
Find if a NodeJS module is available to require or not
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
node_modules |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
}; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
{ | |
"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": "[email protected]: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" | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Can be also achieved by using
require.resolve
(which doesn't load the module):