1

I am trying to export a module to my routes file.

My file tree goes like

routes.js
app.js
controllers/users.js
            posts.js

on my app.js I exported var route = require('./routes'); and that works. now on my routes.js I tried to export require('./controllers');.

But it keeps telling me that it cannot find module controllers.

Doing this works:

require('./controllers/users')

But I am trying to follow expressjs sample initial projects format. And it is bugging me because the example of expressjs shows: (express routes is a folder)

var routes = require('./routes');

and loads it like

app.get('/', routes.index);

with no error. and that ./routes is a folder. I am just following the same principle.

1

3 Answers 3

4

If you try to require a directory, it expects there to be an index.js file in that directory. Otherwise, you have to simply require individual files: require('./controllers/users'). Alternatively, you can create an index.js file in the controllers directory and add the following:

module.exports.users = require('./users');
module.exports.posts = require('./posts');

and then import: var c = require('./controllers');. You can then use them via c.users and c.posts.

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

2 Comments

So how do I call the exports I have on the users.js?
@majimboo Not sure if I understand your question. See here for further details on the module object.
1

You have to understand how require() works.

In your case it fails to find a file named controller.js so it assumes it's a directory and then searches for index.js specifically. That is why it works in the express example.

For your usecase you can do something like this -

var controllerPath = __dirname + '/controllers';
fs.readdirSync(controllerPath).forEach(function(file) {
    require(controllerPath + '/' + file);
});

Comments

1

From: http://nodejs.org/api/modules.html

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.node is a file, load X/index.node as binary addon. STOP

So, if a directory has an index.js, it will load that.

Now, look @ expressjs

http://expressjs.com/guide.html

create : myapp/routes

create : myapp/routes/index.js

Taking some time to really read how modules work is time well spent. Read here

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.