Jo Liss
Jo Liss

Reputation: 33124

Check if package is available?

I'd like to know if require(pkgName) would succeed, that is, if the package with name pkgName is available. How do I best test for that?

I know I can do

try {
  require(pkgName)
} catch (err) {
  available = false
}

but this swallows load errors, and I'd also like to avoid require'ing the package if possible.

Upvotes: 0

Views: 307

Answers (3)

josh3736
josh3736

Reputation: 145152

The best way is to use require.resolve(), since it does not actually run any code contained in the module.

Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.

Just like require, resolve throws if the module is not found, so it needs to be wrapped in try/catch.

Upvotes: 3

robertklep
robertklep

Reputation: 203554

Don't think you can work around using require, but you can specifically check for MODULE_NOT_FOUND errors:

function moduleExists(mod) {
  try {
    require(mod);
  } catch(e) {
    if (e.code === 'MODULE_NOT_FOUND')
      return false;
    throw e;
  };
  return true;
}

Upvotes: 1

Rouan
Rouan

Reputation: 1

I'm showing with the "swig" module. There might be better ways, but this works for me.

var swig; 
try { 
    swig = require('swig');
} catch (err) {
    console.log(" [FAIL]\t Cannot load swig.\n\t Have you tried installing it? npm install swig");
}
if (swig != undefined) {
    console.log(" [ OK ]\t Module: swig");
}

Upvotes: 0

Related Questions