2013-03-19 57 views
0

我想为使用Node.js和CoffeeScript编写的应用程序声明全局变量。所以我将它声明在一个公共文件中,在编译后与两个应用程序连接。在那个文件中,我有例如:使用node.js和CoffeeScript访问全局变量

root = exports ? this 
root.myVariable = 300 

所以我的第一个应用程序是一个HTML的。当我尝试访问此变量时,例如通过

console.log myVariable 

它没有问题。但是我的其他应用程序是由node命令激活的服务器应用程序,我无法在该应用程序中访问该变量。我想:

console.log root.myVariable 
console.log myVariable 

随着第一线我越来越“未定义”打印(所以它看起来该根被定义),并用第二个,我得到的ReferenceError - MYVARIABLE是未定义的。

那么我怎样才能访问这个变量?

这里是在Javascript的输出码我搞定了,我想这可能是有益的:

(function() { 
    var root, _ref; 

    root = (_ref = typeof module !== "undefined" && module !== null ? module.exports : void 0) != null ? _ref : this; 

    root.myVariable = 300; 

}).call(this); 

(function() { 

    console.log(root.myVariable); 

    console.log(myVariable); 

}).call(this); 
+0

你想在'node.js'声明一个全局(一般可变)变量,或者你想声明一个常量(不可变)变量,可以从客户端和服务器js访问? – 2013-03-19 11:15:01

+0

@ leonid-beschastny嗯,实际上它应该是一个从这两个应用程序读取的常量值。 – krajol 2013-03-19 11:18:46

回答

2

你靠近,但你需要改变的东西只是一点点

# config.coffee 
module.exports = 
    foo: "bar" 
    hello: "world" 
    db: 
    user: naomik 
    pass: password1 

# lib/a.coffee 
config = require "../config" 

# lib/b.coffee 
config = require "../config" 

# lib/db.coffee 
dbconfig = require("../config").db 
+0

'module.exports'将在客户端抛出一个异常。 – 2013-03-19 16:16:59

+1

@naomik需要配置才是我需要的,谢谢! – krajol 2013-03-20 19:33:51

0

客户端和服务器JavaScript(或CoffeeScript)的工作方式不同。所以,编写一个可以在两个应用程序中工作的模块非常困难。

有很多库可以解决这个问题,比如RequireJSBrowserify

但我有两个更简单的问题建议。


第一个是使用JSON来存储您的全局常量。在服务器端,你可以简单地requireJSON文件:

root = require './config.json' 

在客户端,您可能会手动解析它或为它服务作为pjson


我的第二个建议是编写一个非常简单的模块,它将与您的应用程序兼容。它会是这个样子:

root = 
    myVariable: 300 
    myOtherVariable: 400 

modulte.exports = root if module?.parent? 

此代码应与这两个node.jsrequire功能和浏览器<script>标签兼容。

更新:

我只是重读你的问题,并意识到,我建议你已经做的差不多。但是你的代码对我来说看起来很好。您可以尝试使用module.export,而不是它的别名exports,它可以帮助:

root = modulte?.exports ? this 
root.myVariable = 300 

但是,正如我所说,你的代码看起来好像没什么问题为好。

+0

感谢您的回复,但不幸的是,使用module.export后结果仍然相同。我在Coffeescript编译后用输出更新了我的问题,也许它可能有用。 – krajol 2013-03-19 12:51:53

+0

@krajol,你需要你的模块才能从服务器代码访问它吗? 'root = require'。/ root.coffee''? – 2013-03-19 13:37:56