node package manager
We need your input. Help make JavaScript better: Take the 2017 JavaScript Ecosystem survey »

safe-require

safe-require

A function that acts pretty much like require but returns undefined when the module is not found (instead of throwing an exception).

Usage

$ npm install safe-require
(...)
$ node
> var safeRequire = require('safe-require')
undefined
> safeRequire('url') // loads any module, local or not, just as require()
{ parse: [Function: urlParse],
  resolve: [Function: urlResolve],
  resolveObject: [Function: urlResolveObject],
  format: [Function: urlFormat],
  Url: [Function: Url] }
> safeRequire('nonexistent') // require('nonexistent') would throw "Cannot find module 'nonexistent'"
undefined