27

I'm looking for a way to find out if a module is available.

For example, I want to check if the module mongodb is available, programmatically.

Also, it shouldn't halt the program if a module isn't found, I want to handle this myself.

PS: I added this question because Google isn't helpful.

4

5 回答 5

28

如果您只想检查模块是否可用(但如果不可用则不加载它),还有一种更聪明的方法:

function moduleAvailable(name) {
    try {
        require.resolve(name);
        return true;
    } catch(e){}
    return false;
}

if (moduleAvailable('mongodb')) {
    // yeah we've got it!
}
于 2015-10-11T17:28:18.910 回答
16

Here is the most clever way I found to do this. If anyone has a better way to do so, please point it out.

var mongodb;
try {
    mongodb = require( 'mongodb' );
}
catch( e ) {
    if ( e.code === 'MODULE_NOT_FOUND' ) {
        // The module hasn't been found
    }
}
于 2012-07-22T13:31:34.127 回答
0

也许resolve-like 模块在这里会有所帮助?

模块的数量存在于 npm 上:

我先写了,async-resolve例如:

var Resolver = require('async-resolve');
var resolver_obj = new Resolver();
resolver_obj.resolve('module', __dirname, function(err, filename) {
  return console.log(filename);
});

它使用node模块路径解析规则,但不会像node它那样阻塞主循环。结果你得到文件名,所以它可以用来决定它的本地模块或全局和其他东西。

于 2016-04-22T11:27:33.943 回答
0

带有 1 行代码的 ES6 简单解决方案:

const path = require('path');
const fs = require('fs');

function hasDependency(dep) {
        return module.paths.some(modulesPath => fs.existsSync(path.join(modulesPath, dep)));
}
于 2017-06-05T22:46:45.487 回答
-9

使用 ES6 箭头函数

var modulePath = m => { try { return require.resolve(m) } catch(e) { return false } }
于 2016-03-12T19:20:11.977 回答