nodeJS require.paths解决问题 [英] nodeJS require.paths resolve problem
问题描述
我试图相对而神秘地要求一个文件以下内容正在发生
I am trying to require a file relatively and mysteriously the following is happening
这很好用,指向 / 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")
结果:
"/Users/marcos/Desktop/Taper/lib/utils"
无论如何?
提前致谢
推荐答案
更新:
来自文档:
前缀为的模块
'/'
是文件的绝对路径。对于
示例,require('/ home / marco / foo.js')
将加载文件
/ home /marco/foo.js
。
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
.
以'为前缀的模块./'
是相对于调用 require()
的文件。
也就是说, circle.js
必须与 foo.js
位于同一目录中$ $ $ b 要求('./ circle')
找到它。
A module prefixed with './'
is relative to the file calling require()
.
That is, circle.js
must be in the same directory as foo.js
for
require('./circle')
to find it.
没有前导'/'或'。 /'表示文件,该模块是
a核心模块或从 node_modules
文件夹加载。
Without a leading '/' or './' to indicate a file, the module is either
a "core module" or is loaded from a node_modules
folder.
如果给定路径不存在, require()
将抛出一个错误,其中
为代码
属性设置为'MODULE_NOT_FOUND'
。
If the given path does not exist, require()
will throw an Error with
its code
property set to 'MODULE_NOT_FOUND'
.
这是原始答案,引用 require.paths
(不再支持):
来自文档:
在节点中, require.paths
是一个字符串数组,表示要搜索模块的路径。没有前缀'/'
,'./'
,或'../'
。
In node, require.paths
is an array of strings that represent paths to be searched for modules when they are not prefixed with '/'
, './'
, or '../'
.
(强调我的)
这篇关于nodeJS require.paths解决问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!