javascript - nodeJS require.paths 解决问题

标签 javascript node.js relative-path require commonjs

我试图相对神秘地要求一个文件,发生了以下情况

这很好,它指向 /Users/marcos/Desktop/Taper/lib/utils.js

myPath = "/Users/marcos/Desktop/Taper/lib/./utils";
require(myPath);

这不是,但它应该指向完全相同的文件:

require.paths.unshift("/Users/marcos/Desktop/Taper/lib")
require("./utils"); //Doesn't work with './'
require("utils"); //Works Fine

任何人都知道为什么在这种情况下我仍然不能使用 ./ 来加载路径,因为

require("path").resolve("/Users/marcos/Desktop/Taper/lib", "./utils")

结果:

"/Users/marcos/Desktop/Taper/lib/utils"

不管怎样?

提前致谢

最佳答案

更新:

来自 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 calling require(). That is, circle.js must be in the same directory as foo.js for require('./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 its code property set to 'MODULE_NOT_FOUND'.


这是原始答案,指的是 require.paths(不再支持):

来自 documentation :

在 Node 中,require.paths 是一个字符串数组,表示要搜索模块的路径当它们没有以 '/' 为前缀时,'./',或 '../'.

(强调我的)

关于javascript - nodeJS require.paths 解决问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5390886/

相关文章:

javascript - vendor Assets 文件夹仅显示 .gitkeep Rails

node.js - 应用程序所有者获得错误的访问 token

node.js - Lambda 层 node_modules

javascript - js,对象状态监控

php - 在 PHP 中检查相对与绝对路径/URL

javascript - 根据浏览器窗口大小更改 Youtube 播放器屏幕大小

javascript - 如何为 Javascript for 循环添加服务器端延迟?

javascript - Angularjs指令手动绑定(bind)模板

Python:Tkinter 接受的位图和图标

java - 使用 JFileChooser 读取文件名