Kuan Kuan - 6 months ago 25
Node.js Question

How to know what path to specify in Node for require


When I use Express.js(but I believe this is more of a Node question), if I want to import some modules, I need to use require(module path).

But I am a little confused what root path should be used for each require, are they all same to the path we execute the node command?

Sometime, It works when I use require("../modelname") while sometimes require("./modelname") even I did not change the modelname.js location.



If you are in a directory where you want to access modelname there are two scenarios given below

  1. if modelname is in the same directory then you can use require("./modelname")

  2. if calling directory is different and one level above to your modelname directory then you have to use require("../modelname").