Javascript nodeJS require.paths 解决问题
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5390886/
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
nodeJS require.paths resolve problem
提问by zanona
I am trying to require a file relatively and mysteriously the following is happening
我正在尝试相对而神秘地需要一个文件,但正在发生以下情况
This works well which points to /Users/marcos/Desktop/Taper/lib/utils.js
这很有效,这表明 /Users/marcos/Desktop/Taper/lib/utils.js
myPath = "/Users/marcos/Desktop/Taper/lib/./utils";
require(myPath);
This doesn't but it should point to exactly the same file:
这不是,但它应该指向完全相同的文件:
require.paths.unshift("/Users/marcos/Desktop/Taper/lib")
require("./utils"); //Doesn't work with './'
require("utils"); //Works Fine
Anyone knows why I can't still use ./
in this case for loading the path since
任何人都知道为什么我./
在这种情况下仍然不能用于加载路径,因为
require("path").resolve("/Users/marcos/Desktop/Taper/lib", "./utils")
results in:
结果是:
"/Users/marcos/Desktop/Taper/lib/utils"
anyway?
反正?
Thanks in advance
提前致谢
回答by Martijn
UPDATED:
更新:
From the documentation:
从文档:
A module prefixed with
'/'
is an absolute path to the file. For example,require('/home/marco/foo.js')
will load the file at/home/marco/foo.js
.A module prefixed with
'./'
is relative to the file callingrequire()
. That is,circle.js
must be in the same directory asfoo.js
forrequire('./circle')
to find it.Without a leading '/' or './' to indicate a file, the module is either a "core module" or is loaded from a
node_modules
folder.If the given path does not exist,
require()
will throw an Error with itscode
property set to'MODULE_NOT_FOUND'
.
前缀
'/'
为 的模块是文件的绝对路径。例如,require('/home/marco/foo.js')
将在/home/marco/foo.js
.前缀
'./'
为的模块相对于文件调用require()
. 也就是说,circle.js
必须在与foo.js
for相同的目录中require('./circle')
才能找到它。如果没有前导 '/' 或 './' 来指示文件,则该模块要么是“核心模块”,要么是从
node_modules
文件夹加载的。如果给定的路径不存在,
require()
将抛出一个错误,其code
属性设置为'MODULE_NOT_FOUND'
。
Here's the original answer, which refers to require.paths
(which is no longer supported):
这是原始答案,它指的是require.paths
(不再支持):
From the documentation:
从文档:
In node, require.paths
is an array of strings that represent paths to be searched for modules when they are not prefixed with '/'
, './'
, or '../'
.
在节点中,require.paths
是表示要搜索的模块路径的字符串数组时它们不与前缀'/'
,'./'
或'../'
。
(emphasis mine)
(强调我的)
回答by vimdude
You can pass that using NODE_PATH
你可以通过使用 NODE_PATH
Example:
例子:
NODE_PATH=`pwd` node app.js
回答by Nadav Leshem
I created a new node module called rekuire.
我创建了一个名为rekuire的新节点模块。
It allows you to "require" without using relative paths.
它允许您在不使用相对路径的情况下“要求”。
It's a big time saver when it comes to testing/refactoring.
在测试/重构方面,这是一个很大的节省时间。