module.paths
存储 的搜索路径数组require
。搜索路径相对于require
调用的当前模块。所以:
var fs = require("fs");
// checks if module is available to load
var isModuleAvailableSync = function(moduleName)
{
var ret = false; // return value, boolean
var dirSeparator = require("path").sep
// scan each module.paths. If there exists
// node_modules/moduleName then
// return true. Otherwise return false.
module.paths.forEach(function(nodeModulesPath)
{
if(fs.existsSync(nodeModulesPath + dirSeparator + moduleName) === true)
{
ret = true;
return false; // break forEach
}
});
return ret;
}
和异步版本:
// asynchronous version, calls callback(true) on success
// or callback(false) on failure.
var isModuleAvailable = function(moduleName, callback)
{
var counter = 0;
var dirSeparator = require("path").sep
module.paths.forEach(function(nodeModulesPath)
{
var path = nodeModulesPath + dirSeparator + moduleName;
fs.exists(path, function(exists)
{
if(exists)
{
callback(true);
}
else
{
counter++;
if(counter === module.paths.length)
{
callback(false);
}
}
});
});
};
用法:
if( isModuleAvailableSync("mocha") === true )
{
console.log("yay!");
}
或者:
isModuleAvailable("colors", function(exists)
{
if(exists)
{
console.log("yay!");
}
else
{
console.log("nay:(");
}
});
编辑:注意:
module.paths
不在API中
- Documentation states that you can add paths that will be scanned by
require
but I couldn't make it work (I'm on Windows XP).