我正在寻找一种方法来确定模块是否可用。例如,我想以编程方式检查是否可用
注:我添加了这个问题是因为谷歌没有提供有用的结果。
mongodb
模块。同时,如果未找到模块,程序不应该停止,我希望自己处理这个问题。注:我添加了这个问题是因为谷歌没有提供有用的结果。
mongodb
模块。同时,如果未找到模块,程序不应该停止,我希望自己处理这个问题。如果你只想检查一个模块是否可用(但不需要在其未加载时加载它),有一种更巧妙的方法:
如果你只想检查一个模块是否可用(但不需要在其未加载时加载它),有一种更巧妙的方法:
function moduleAvailable(name) {
try {
require.resolve(name);
return true;
} catch(e){}
return false;
}
if (moduleAvailable('mongodb')) {
// yeah we've got it!
}
var mongodb;
try {
mongodb = require( 'mongodb' );
}
catch( e ) {
if ( e.code === 'MODULE_NOT_FOUND' ) {
// The module hasn't been found
}
}
对于 ECMAScript 模块(ESM),自从 Node 12 版本以来,import
关键字也可以被用作函数返回一个 Promise:
import("mongodb")
.then(mongodb => {
// use module
})
.catch(e => console.error(e)) // The module hasn't been found
或者
async main() {
const mongodb = import("mongodb")
// use module
}
main().catch(e => console.error(e)) // module hasn't been found or other error
也许类似于resolve
的模块会对这里有所帮助?
在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
那样阻塞主循环。结果你会得到文件名,因此可以用来决定它是本地模块还是全局模块以及其他事情。
使用一行代码的ES6简单解决方案:
const path = require('path');
const fs = require('fs');
function hasDependency(dep) {
return module.paths.some(modulesPath => fs.existsSync(path.join(modulesPath, dep)));
}
使用ES6箭头函数
var modulePath = m => { try { return require.resolve(m) } catch(e) { return false } }
MODULE_NOT_FOUND
。为了避免这种情况,可以在消息上使用正则表达式来检查哪个模块没有找到。最好将实际的错误信息打印到控制台上。首先使用require.resolve
可以避免这种情况。 - vaughan