是否可以判断模块/包是否可用?
类似这样的事情:
var moduleexists = require "moduleexists"
if (moduleexists("strangemodule")) {
var strangemodule = require("strangemodule");
strangeModule.doCoolStuff();
} else {
// Do something without strangemodule
}
最佳答案
您可以使用try..catch
加载模块
try {
var m = require('idontexist');
} catch(e) {
var m = {
'doCoolStuff': function() {
..
}
};
}
if (m.hasOwnProperty('doCoolStuff') && typeof m.doCoolStuff === 'function') {
m.doCoolStuff();
}
关于node.js - 仅需要一个模块(如果已安装),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19852013/