简体   繁体   中英

node.js require relative paths

I have node.js modules in several directories because I am following MVC pattern. I am in need to call require to several modules which are located outside current directory. How can I do that?

/app/controller/c1.js

...


/app/model/m1.js

...


/app/view/v1.js

...


/app/view/v2.js

// this works
require('./v2'); 

// these doesn't work 
require('../model/m1.js');
require('~/model/m1.js');

...

Why is that so?

For modules in other directories, use the format:

testAuth =require('./public/javascripts/test.js'), 
//in case the test.js is in the public/javascripts directory (I am using Linux)

If you skip the '.js' extension, node should look for .js first before .json etc.

hope it helps.

check out this project

https://github.com/nadav-dav/rekuire

it allows you to use "require" without the relative paths, just stating the file/class name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM