在Node.js中,如何加载我的模块一次,然后在整个应用程序中使用它们? [英] In Node.js, how can I load my modules once and then use them throughout the app?

查看:146
本文介绍了在Node.js中,如何加载我的模块一次,然后在整个应用程序中使用它们?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个全局模块文件,然后让我的所有文件都需要该全局模块文件。在该文件中,我将加载所有模块一次并导出已加载模块的字典。

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.

我该怎么做?

我实际上尝试创建此文件...每次我 require('global_modules')时,所有模块不断重装。这是O(n)。

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。使用魔术变量(声明没有 var



使用魔法全局变量,不带 var

示例:

fs = require("fs");

而不是

var fs = require("fs");

如果你没有把 var 当声明变量,变量将是魔法全局

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

推荐这个。特别是,如果你处于严格模式(use strict),那根本不会起作用。

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

附加到 global object成为全局变量,可以从应用程序的任何地方访问。

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

所以,你可以这样做:

global.fs = require("fs");

这并不像 1那样糟糕。,但仍然可以避免可能。

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

对于你的例子:

让我们说你有两个文件: server.js (主文件)和 global_modules.js 文件。

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

server.js 中你会这样做:

require("./global_modules");

global_modules.js 你将拥有:

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

global._modules = {...}

server.js 你将能够:

_modules.account_controller // returns require('/account/controller.js'),

这篇关于在Node.js中,如何加载我的模块一次,然后在整个应用程序中使用它们?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆