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

孤街醉人 提交于 2020-01-01 12:33:30

问题


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


来源:https://stackoverflow.com/questions/20599002/in-node-js-how-can-i-load-my-modules-once-and-then-use-them-throughout-the-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!