Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.js module loading

Node.js module loading


I am currently building a web app with Node and I am curious as to how Node loads its required files or modules.

I am using express for view and server config, however I am finding that all the Node examples (I know express offers an MVC example) don't really conform to the general MVC pattern. I am also aware that Node is not necessarily suited for MVC, but bear with me, because I like MVC.

If you consider the following route declaration, it would be effective to use this as a controller, since here you can control the request and response logic:

module.exports = function (app) {

app.get('/', function (req, res) {

    res.render('index', { layout: false });


To try and follow an MVC architecture I have effectively divided the routes up into its relevant paths in effect creating controllers. However whenever I have a different route file it must contain its own set of required modules. For example:

var mongo = require('mongoskin');

I would then declare the required route files in the app.js or server.js file that holds the server config settings.

I am wondering whether splitting up the routes like this would slow down the application since I am unaware of how Node loads its modules. If it is loading as per needed then surely this implementation must slow it down?

Problem courtesy of: kryptogeek


Required modules are only loaded once and then cached, so feel free the break up your app into as many modules as needed to cleanly organize your app. If you have 20 files that call require('mongoskin'), that module is still only loaded once.

Solution courtesy of: JohnnyHK


View additional discussion.

This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.js module loading


Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription