我检查了这个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/