nodeJS require.paths resolve problem

删除回忆录丶 提交于 2019-12-21 04:08:42

问题


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

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


回答1:


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 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'.


Here’s the original answer, which refers to require.paths (which is no longer supported):

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 '../'.

(emphasis mine)




回答2:


You can pass that using NODE_PATH

Example:

NODE_PATH=`pwd` node app.js



回答3:


I created a new node module called rekuire.

It allows you to "require" without using relative paths.

It's a big time saver when it comes to testing/refactoring.

https://npmjs.org/package/rekuire



来源:https://stackoverflow.com/questions/5390886/nodejs-require-paths-resolve-problem

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!