Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
25
rated 0 times [  27] [ 2]  / answers: 1 / hits: 47279  / 11 Years ago, mon, january 20, 2014, 12:00:00

I have a directory that looks like this:



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


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


More From » node.js

 Answers
3

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




  • a core module such as fs

  • a relative filepath that you specify in your require call

  • a directory search for the appropriately named module in a node_modules folder somewhere in a parent directory of the file in which the require function is called.



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



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.



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. Use relative file paths.

  2. Package up your desired resource as a real module with a package.json file and drop it into the node_modules folder.



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.


[#73060] Saturday, January 18, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jonrened

Total Points: 627
Total Questions: 114
Total Answers: 99

Location: Zimbabwe
Member since Thu, Jul 21, 2022
2 Years ago
jonrened questions
Mon, Nov 2, 20, 00:00, 4 Years ago
Tue, May 19, 20, 00:00, 4 Years ago
Tue, Jan 21, 20, 00:00, 4 Years ago
Thu, Nov 7, 19, 00:00, 5 Years ago
;