jeudi 26 février 2015

Where are required modules visible?

I have a problem understanding NodeJS require(). Basically I have this 3 files:


moongooseconfig.js



var config = require('./config');
var mongoose = require('mongoose');

module.exports = function() {
var db = mongoose.connect(config.db);
require('../app/models/user.server.model');

return db;
}


usercontroller.js



var User = require('mongoose').model('User');

exports.create = function(req, res, next) {
var user = new User(req.body);
user.save(function(err) {
if(err) {
return next(err);
} else {
res.json(user);
}
});
};


And the server.js



process.env.NODE_ENV = process.env.NODE_ENV || 'development';
var mongoose = require('./config/mongooseconfig');
var express = require('./config/express');


var db = mongoose();
var app = express();
app.listen(3000);


My understanding of require was that the required module is only visible in the JS file which required the module. I do not get why the user controller can use the mongoose Model 'User' without requiring the model file. Yet the mongooseconfig requires the model file inside a function without saving it to a variable.


Can somebody tell me what happens there? Can every file access modules once they where required anywhere? (Maybe I 'm just to blind, but I can not find the answer in the Node docs and googling "nodejs require scope" does not gave me any good results)


Aucun commentaire:

Enregistrer un commentaire