node.js 如何检查节点是否存在模块以及是否存在加载?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21740309/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to check in node if module exists and if exists to load?
提问by Damir
I need to check if file/(custom)module js exists under some path. I tried like
我需要检查文件/(自定义)模块 js 是否存在于某个路径下。我试过
var m = require('/home/test_node_project/per');
but it throws error when there is no per.js in path.
I thought to check with
fsif file exists but I don't want to add '.js'as suffix if is possible to check without that.
How to check in node if module exists and if exists to load ?
var m = require('/home/test_node_project/per');
但是当路径中没有 per.js 时它会抛出错误。我想检查
fs文件是否存在,但我不想添加'.js'作为后缀,如果没有的话可以检查。如何检查节点是否存在模块以及是否存在加载?
回答by Chev
Require is a synchronous operation so you can just wrap it in a try/catch.
Require 是一个同步操作,因此您可以将它包装在 try/catch 中。
try {
var m = require('/home/test_node_project/per');
// do stuff
} catch (ex) {
handleErr(ex);
}
回答by Louis
You can just try to load it and then catch the exception it generates if it fails to load:
您可以尝试加载它,然后在加载失败时捕获它生成的异常:
try {
var foo = require("foo");
}
catch (e) {
if (e instanceof Error && e.code === "MODULE_NOT_FOUND")
console.log("Can't load foo!");
else
throw e;
}
You should examine the exception you get just in case it is not merely a loading problem but something else going on. Avoid false positives and all that.
你应该检查你得到的异常,以防它不仅仅是加载问题,而是发生了其他事情。避免误报等等。
回答by joeytwiddle
It is possible to check if the module is present, without actually loading it:
可以检查模块是否存在,而无需实际加载它:
function moduleIsAvailable (path) {
try {
require.resolve(path);
return true;
} catch (e) {
return false;
}
}
Documentation:
文档:
require.resolve(request[, options])
Use the internal require() machinery to look up the location of a module, but rather than loading the module, just return the resolved filename.
require.resolve(request[, options])
使用内部 require() 机制查找模块的位置,但不加载模块,只需返回解析的文件名。
Note: Runtime checks like this will work for Node apps, but they won't work for bundlers like browserify, WebPack, and React Native.
注意:像这样的运行时检查适用于 Node 应用程序,但不适用于 browserify、WebPack 和 React Native 等打包程序。
回答by Jaroslav
You can just check is a folder exists by using methods:
您可以使用以下方法检查文件夹是否存在:
var fs = require('fs');
if (fs.existsSync(path)) {
// Do something
}
// Or
fs.exists(path, function(exists) {
if (exists) {
// Do something
}
});

