node.js - 使用coffeescript的 Node 中的全局变量

标签 node.js coffeescript express

我检查了这个How do I define global variables in CoffeeScript? 用于声明全局变量,即在 app.js 中声明并在 routes/index.coffee 中访问

我在 app.coffee 中声明 (exports ? this).db = redis.createClient() 并尝试使用 db.set('online',Date.now() 访问 routes.index.coffee 中的数据库, (err,reply) -> console.log(reply.toString()) ) 这似乎不起作用......发生了什么......我在 Node 0.8.9

还有其他方法可以使用,但很想知道发生了什么...... 还尝试了 app.coffee 中的 @db = redis.createClient() ,它也不起作用

谢谢

最佳答案

exports没有定义“globals;”它定义了通过 require 可用的模块的“public”成员.另外,exports总是初始定义并且 exports === this , 所以 (exports ? this)实际上并没有做任何事情。

但是,由于全局变量通常不被接受(并且确实违背了 Node 模块系统的某些意图),Web 应用程序的一种常见方法是定义允许访问 db 的自定义中间件。作为 req 的属性或 res对象:

# app.coffee
app.use (req, res, next) ->
  req.db = redis.createClient()
  next()
# routes/index.coffee
exports.index = (req, res) ->
  req.db.set('online', Date.now(), (err,reply) -> console.log(reply))

这方面的一个例子可以在 decorate.js 中找到。的 npm-www npmjs.org 后面的存储库:

function decorate (req, res, config) {
  //...

  req.model = res.model = new MC

  // ...

  req.cookies = res.cookies = new Cookies(req, res, config.keys)
  req.session = res.session = new RedSess(req, res)

  // ...

  req.couch = CouchLogin(config.registryCouch).decorate(req, res)

  // ...
}

不过,如果您仍然愿意定义 db作为全局变量,Node.JS 定义了一个 global您可以附加到的变量:

global.db = redis.createClient()

关于node.js - 使用coffeescript的 Node 中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12465615/

相关文章:

javascript - 如何在 node.js 中分配并行任务

CoffeeScript 未定义

node.js - 如何默认将错误返回为 JSON 而不是带有 express 的 HTML?

node.js - 重试连接 postgres Nodejs

javascript - 在客户端压缩图像(AngularJS)并上传到服务器(NodeJS)

Node.JS Express 4 - Mongoose 不保存数据

javascript - WebRTC 直播视频流 node.js

coffeescript - 如何自定义 Wintersmith 分页器?

javascript - 获取 Restangular 对象属性

regex - Express.js : how to make app. 在 req.param 中得到 ('/[:userId]i' ..)?