How to find out which path to specify in Node for a request

All:

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 about which root path should be used for each request, are they the same for the path we are executing the Node command?

Sometime, it works when I use require ("../modelname") and sometimes I require ("./modelname") even I haven't changed the location of modelname.js.

thank

+3


source to share


4 answers


If you are in the directory where you want to access modelname

, here are two scripts



  • If modelname

    is in the same directory, you can userequire("./modelname")

  • If the calling directory is different from one level above your directory modelname

    , then you should use require("../modelname")

    .

+2


source


Node documentation provides a pseudocode algorithm for how it resolves the path forrequire()

Summarizing:



require(X) from module at path Y
If X begins with './' or '/' or '../'
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)

LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text.  STOP
2. If X.js is a file, load X.js as JavaScript text.  STOP
3. If X.json is a file, parse X.json to a JavaScript Object.  STOP
4. If X.node is a file, load X.node as binary addon.  STOP

LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
   a. Parse X/package.json, and look for "main" field.
   b. let M = X + (json main field)
   c. LOAD_AS_FILE(M)
2. If X/index.js is a file, load X/index.js as JavaScript text.  STOP
3. If X/index.json is a file, parse X/index.json to a JavaScript object. STOP
4. If X/index.node is a file, load X/index.node as binary addon.  STOP

      

+3


source


When you execute require( 'express' )

, node will start in your current folder and grow the file tree until it finds the folder with package.json

.

Once it finds this file, it checks for the folder node_modules

and looks for it node_modules/express

. It will then follow the instructions node_modules/express/package.json

on how to include the module.

If you want to require your own code that is missing package.json

, you would do something like this.

require( './router' )

or

require( '../middleware/site-data' )

The first example .

refers to the folder that the importing file is in and will import either ./router.js

or ./router/index.js

whichever exists. B require

, .

effectively transforms into __dirname + '/'

.

In the second example, ..

refers to the parent directory where the importing file is located. B require

, ..

actually translated into __dirname + '/../'

.

Good luck!

+1


source


use the webstorm tool where you have a debugging tool like we have in eclipse, run your application in debug mode and set breakpoints.

0


source







All Articles