majidarif
majidarif

Reputation: 19985

NodeJS cannot find custom module

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.

Upvotes: 1

Views: 11393

Answers (3)

bryanmac
bryanmac

Reputation: 39296

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

Upvotes: 1

Mukesh Soni
Mukesh Soni

Reputation: 6668

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);
});

Upvotes: 1

dparpyani
dparpyani

Reputation: 2493

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.

Upvotes: 4

Related Questions