JJJollyjim
JJJollyjim

Reputation: 6237

Only require a module if it is installed

Is it possible to tell if a module/package is available to use?

Something like this:

var moduleexists = require "moduleexists"

if (moduleexists("strangemodule")) {
  var strangemodule = require("strangemodule");

  strangeModule.doCoolStuff();
} else {
  // Do something without strangemodule
}

Upvotes: 2

Views: 59

Answers (1)

Bulkan
Bulkan

Reputation: 2592

You can use try..catch to load the module in

try {                                                                                                                                                                                                                     
  var m = require('idontexist');                                                                                                                                                                                                                  
} catch(e) {                                                                                                                                                                                                                                      
 var m = {
    'doCoolStuff': function() { 
      .. 
    }
 };                                                                                                                                                                                                                             
} 

if (m.hasOwnProperty('doCoolStuff') && typeof m.doCoolStuff === 'function') {
   m.doCoolStuff();
}                                                                                                                                                                                                                                                                                                                                                                                                                                 

Upvotes: 3

Related Questions