[英]Check if a node.js module is available
我正在尋找一種方法來確定模塊是否可用。
例如,我想以編程方式檢查模塊mongodb
是否可用。
另外,如果找不到模塊,它不應該停止程序,我想自己處理。
PS:我添加了這個問題,因為谷歌沒有幫助。
如果您只想檢查模塊是否可用(但如果不可用則不加載它),還有一種更聰明的方法:
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
}
}
也許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
那樣阻塞主循環。 結果你得到文件名,所以它可以用來決定它的本地模塊或全局和其他東西。
帶有 1 行代碼的 ES6 簡單解決方案:
const path = require('path');
const fs = require('fs');
function hasDependency(dep) {
return module.paths.some(modulesPath => fs.existsSync(path.join(modulesPath, dep)));
}
對於自 Node 12 起的 ECMAScript 模塊(ESM), 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
使用 ES6 箭頭函數
var modulePath = m => { try { return require.resolve(m) } catch(e) { return false } }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.