gpt4 book ai didi

node.js - 如果已安装,则只需要一个模块

转载 作者:搜寻专家 更新时间:2023-11-01 00:45:29 26 4
gpt4 key购买 nike

是否可以判断模块/包是否可用?

像这样:

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com