节点需要绝对路径 [英] Node require absolute path

查看:73
本文介绍了节点需要绝对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的目录:

I have a directory that looks like this:

-- app/
   |- models/
      |- user.js
   |- config.json

我想要我的 user.js 文件需要 config.json 。目前,我正在使用 require(’/ config'),但这无法正常工作。我究竟做错了什么?我想避免使用 require('../ config')

I want my user.js file to require config.json. Right now I'm using require('/config') but this is not working. What am I doing wrong? I'd like to avoid using require('../config').

推荐答案

简单的答案是您没有做错任何事情。通过一点研究,require函数将查找以下内容之一:

The simple answer is that you aren't doing anything wrong. Per a little research, the require function looks for one of:


  • 诸如fs

  • <之类的核心模块li>您在require调用中指定的相对文件路径
  • 目录在名为require函数的文件的父目录中的某个位置的node_modules文件夹中搜索适当命名的模块。

请参见: http://www.bennadel.com/blog/2169-Where-Does-Node-js-And-Require-Look- For-Modules-.htm
并且: http://nodejs.org /api/modules.html#loading_from_node_modules_Folders

以上两个资源均具有修改NODE_PATH环境变量的功能,但这听起来像是一种非常糟糕的做法,最起码会使您的代码的可移植性降低。对于config.json这样的文件,它也可能甚至无法工作,因为尽管我从未做过,但我想更改NODE_PATH变量只会更改require()查找与真实模块相对应的package.json文件的位置。

Both resources above reference the ability to also modify a NODE_PATH environment variable, however this sounds like very bad practice and at a minimum would make your code way less portable. It also probably wouldn't even work for a file like config.json since, though I'd never done it, I'd imagine changing the NODE_PATH variable only changes where require() looks for package.json files corresponding to real modules.

摘要,请参见: Piotr Kowalczuk在上文中引用。对于该帖子,您有两个实际选择:

In summary, see: How to make the require in node.js to be always relative to the root folder of the project? as referenced above by Piotr Kowalczuk. Per that post, you have two real options:


  1. 使用相对文件路径。

  2. 打包

最后,请牢记您的所需资源,将其作为带有package.json文件的真实模块,并将其放入node_modules文件夹中。您尝试做的事情与您正在使用的程序的原则背道而驰。我认为这是一种情况,您可以通过使用Node的粒度并按照设计意图使用相对文件路径来最终使您(和您的协作者)的生活更轻松。

Finally, just bear in mind that what you are trying to do goes against the grain of the program that you are using. I think this is one case where you will ultimately make your life easier (and your collaborators'!) by going with the grain of Node and using relative file paths as the design intends.

这篇关于节点需要绝对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆