Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Find if a NodeJS module is available to require or not
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.
} 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": ""
"homepage": "",
"author": {
"name": "Francois-Guillaume Ribreau",
"url": ""
"devDependencies": {
"nodeunit": "~0.7.4"
"keywords": [
"license": "MIT"
var exist = require('./');
module.exports.nativeModules = function(t){
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");
module.exports.notNativeModules = function(t){
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");

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