0

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?

1

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

see I have "controller" folder next to "config" folder and a file inside controller folder requires file from config folder. so what require would you let me write?
try this: ../config/test.js // where test.js is the file name you are trying to access - let us know if it works for you (this is for Linux)
This line "require('../config/db.js');" is inside AppController module and when AppController is required the same way from other controller, this throws Controller failed to be loaded error.
1

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

1 Comment

But the synthax is a bit cumbersome :( var module = require('rekuire')('module')

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.