In Node.js, how can I load my modules once and the

2019-04-10 07:58发布

问题:

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;

回答1:

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'),


回答2:

require already does it. Try loading a module, modify it and then load it another time in another place or file:

var fs = require('fs'):
console.log(fs.hey);
fs.hey = 'HEY TIMEX, WHATS UP?';
//another place of the same process
var fs = require('fs');
console.log(fs.hey);