2

I worry that if my requiring module changes path I would need to update all required path!! (A thing that would not happen in java)

MyModule.js require('./lib')

Now MyModule changes directory now I need to do

require('../../lib')

Anyway to specify require path as from project root?

require('/lib')

I'm writing this from my mobile sorry if I lack formatting

Jas
  • 14,493
  • 27
  • 97
  • 148
  • 1
    You can't do that. Consider making separate npm packages. – SLaks Jul 25 '16 at 19:03
  • Possible duplicate of this: http://stackoverflow.com/questions/10265798/determine-project-root-from-a-running-node-js-application?rq=1 – Benjamin Kovach Jul 25 '16 at 19:06
  • @Slaks I would but those are really internals to my project I like them part of my project. This feature sounds so basic for me coming from java I don't get how it's not out of the box. – Jas Jul 25 '16 at 19:36
  • @Slaks I would like to accept your answer. I'm not going for a separate npm package because these `js` modules are really internal to my project. In addition I would not want to clutter my global OS `NODE_PATH` because If I have multiple node projects starting up they would each override the others NODE_PATH. which means in my case I just can't do that. – Jas Jul 26 '16 at 06:38

1 Answers1

3

Before running your node app, first run:

Linux: export NODE_PATH=.
Windows: set NODE_PATH=.

You could add it in the npm start script itself so, you can automate it easily.

EXAMPLE:

Directory tree:

my_example/
├── lib
│   ├── a
│   │   └── index.js
│   └── b
│       └── index.js
├── package.json
└── server.js

File Contents:

package.json:

{
  *
  *
  "scripts": {
    "start": "export NODE_PATH=./lib/;node server.js"
  },
  *
  *
}

./lib/a/index.js:

console.log("hi from module a");
require("b/index");

./lib/b/index.js:

console.log("hi from module b");

./server.js:

require("a/index");

OUTPUT on running npm start:

hi from module a
hi from module b
Iceman
  • 6,035
  • 2
  • 23
  • 34
  • Would this mean other developers need to run non start when they work on my project? Also if I toggle between node projects I would need to reset this parameter? – Jas Jul 25 '16 at 19:34
  • when u put it in npm start, then everytime it is run, it will automatically set it before node is run, and pesists for the opened shell and dies after. – Iceman Jul 25 '16 at 19:36
  • @Jas have made an edit to include full example with full details. – Iceman Jul 25 '16 at 19:54