0

I'm in the process of refactoring my server.js file and trying to incorporate MVC pattern. I'm running into a problem trying to access my controller from my routes.js. I've tried just about every variation of absolute and relative path that I can think but I must be missing something. Here is my directory structure: enter image description here

And from my routes.js, here is my code:

module.exports = function ( app, passport, auth ) {
    var Clients = require('controllers/clients');
    app.get('/clients', Clients.list);
}

I don't think this is relevant, but here is my clients controller:

var mongoose = require('mongoose')
    , Client  = mongoose.model('Client');

exports.list = function( req, res ) {
    Client.find( function( err, clients ) {
        res.renderPjax('clients/list', { clients: clients, user: req.user });
    });
}

Here is the error that I'm getting when trying to access my controller from routes:

module.js:340
    throw err;
          ^
Error: Cannot find module 'controllers/clients'
    at Function.Module._resolveFilename (module.js:338:15)
    at Function.Module._load (module.js:280:25)
    at Module.require (module.js:364:17)
    at require (module.js:380:17)
    at module.exports (/Users/sm/Desktop/express3-mongoose-rememberme/app/routes.js:5:16)
    at Object.<anonymous> (/Users/sm/Desktop/express3-mongoose-rememberme/server.js:334:24)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)

I'm sure it's something simple that I'm over looking. How can I access my controller from my routes?

2 Answers 2

2

To require something that isn't a separate package (isn't in node_modules), you need to use an explicitly relative path:

require('./controllers/clients')

For more information, see the documentation.

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

Comments

0

Local Modules

require(...) takes a relative path for local modules

require('./controllers/clients')

Installaed modules

For modules installed via npm install -S foo, use the syntax

require('foo')

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.