node.js - NodeJS - 访问不同模块中的变量

标签 node.js variables module

我正在编写一个基于 mudule express 的 NodeJS 应用程序。以下是我的 app.js 的重要部分:

var express = require('express')
  , routes = require('./routes')
  , passport = require('passport')
  , LocalStrategy = require('passport-local').Strategy;
var app = module.exports = express.createServer();
var ab = 'this is a test!';

// Configuration
app.configure(function(){
  ...

// Routes
app.get('/', routes.index);

app.listen(3000);

Routes.index - 是一个 Controller ,在请求“/”时执行。这是代码:

exports.index = function(req, res){

   passport.serializeUser(function(user, done) {
       done(null, user.id);
    });

    ...

  res.render('index.ejs', {
      title: ab
  })
};

从技术上讲,index.js - 是单独的文件,位于“/routes”文件夹中。因此,当我启动我的应用程序时,它崩溃了,因为找不到在主应用程序中声明的护照 var。此外,ab 也找不到,但是已声明。如果我在 index.js 中重新声明 vars,JS 会为我创建新对象。如何在我的应用程序的每个模块中使用我的变量?我浏览了一些关于 SO 的主题,但是无法理解——这是一个常见问题还是我的应用程序的结构是错误的?谢谢!

最佳答案

正如您所发现的,在一个模块中声明的变量不会神奇地出现在其他模块中。当涉及到护照等模块时,通常人们只是在需要的地方再次要求它们,所以:

应用程序.js:

var passport = require('passport'),
    index = require('./routes/index');

index.js:

var passport = require('passport');

虽然有时候你想传递参数——我经常这样做是为了单元测试,如果我可以传递依赖项,我也可以模拟这些依赖项。或者您有一个应用程序范围的配置要传递。我通常这样做:

应用程序.js:

var ab = "foo",
    index = require('/routes/index')(ab);

index.js:

module.exports = function(ab) {
    // Here I have access to ab and can to what I need to do

    return {
        index: function(req, res) { res.send(ab) }
    }
}

其他人更喜欢“单例”模式,每次您需要一个模块时,您检查它是否已经初始化,如果是,则传递该实例。

关于node.js - NodeJS - 访问不同模块中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11358702/

相关文章:

javascript - 未捕获引用 : variable is not defined

javascript - Typescript 中的导出功能

PowerShell 在运行 Import-Module 时忽略 Write-Verbose

javascript - Nestjs如何控制缓存?

javascript - 何时关闭 MongoDB 连接

javascript - 使用基于视口(viewport)尺寸的 JavaScript 变量来更改 CSS 属性

css - Visual Studio Code 无法识别 CSS 文件中的变量

node.js - 使用 docker-compose 对 Node Express 应用程序进行 Docker 化

mysql - 使用 NodeJS 和 MySql 的 jQuery 数据表

module - 打开 Module_name 给出编译器错误