只有安装了模块才需要
是否有可能判断一个模块/软件包是否可用?
像这样的东西:
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(); }