Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Node.js, how can I load my modules once and then use them throughout the app?

I want to create one global module file, and then have all my files require that global module file. Inside that file, I would load all the modules once and export a dictionary of loaded modules.

How can I do that?

I actually tried creating this file...and every time I require('global_modules'), all the modules kept reloading. It's O(n).

I want the file to be something like this (but it doesn't work):

//global_modules.js - only load these one time
var modules = {
    account_controller: '/account/controller.js',
    account_middleware: '/account/middleware.js',
    products_controller: '/products/controller.js',
    ...
}
exports.modules = modules;
like image 711
TIMEX Avatar asked Dec 25 '22 16:12

TIMEX


1 Answers

1. Using a magic variable (declared without var)

Use magic global variables, without var.

Example:

fs = require("fs");

instead of

var fs = require("fs");

If you don't put var when declaring the variable, the variable will be a magic global one.

I do not recommend this. Especially, if you are in the strict mode ("use strict") that's not going to work at all.

2. Using global.yourVariable = ...

Fields attached to global object become global variables that can be accessed from anywhere in your application.

So, you can do:

global.fs = require("fs");

This is not that bad like 1., but still avoid it when possible.


For your example:

Let's say you have two files: server.js (the main file) and the global_modules.js file.

In server.js you will do this:

require("./global_modules");

and in global_modules.js you will have:

_modules = {
    account_controller: require('/account/controller.js'),
    account_middleware: require('/account/middleware.js'),
    products_controller: require('/products/controller.js'),
    ...
}

or

global._modules = {...}

In server.js you will be able to do:

_modules.account_controller // returns require('/account/controller.js'),
like image 58
Ionică Bizău Avatar answered Dec 28 '22 06:12

Ionică Bizău