简体   繁体   中英

Accessing global variables with node.js and CoffeeScript

I'm trying to declare global variables for my applications that I'm writing using Node.js and CoffeeScript. So I'm declaring it in a common file that is concatenated to both applications after compilation. In that file I have for example:

root = exports ? this
root.myVariable = 300

So my first application is a HTML one. When I try to access this variable, for example by

console.log myVariable

There is no problem with it. But my other application is a server application lauched by node command and I cannot access that variable in that application. I tried:

console.log root.myVariable
console.log myVariable

With first line I'm getting 'undefined' printed (so it looks that root is defined) and with the second one, I'm getting ReferenceError - myVariable is undefined.

So how can I access this variable?

Here is an output code in Javascript that I get, I guess it might be helpful:

(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);

You're close, but you need to change things just a little bit

# 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

Client and server JavaScript (or CoffeeScript ) works differently. So, its a really difficult to write a module that'll work in both applications.

There is a lot of libraries to solve this problem, like RequireJS and Browserify .

But I have two simpler suggestions for your problem.


First one is to use JSON to store your global constants. On the server side you can simply require you JSON file:

root = require './config.json'

On the client side you may either parse it manually or serve it as pjson .


My second suggestion is to write really simple module that'll be compatible with both your applications. It'll look something like this:

root = 
  myVariable: 300
  myOtherVariable: 400

modulte.exports = root if module?.parent?

This code should be compatible with both node.js require function and browser <script> tag.

Update:

I just reread you question and realized, that you've did almost as I suggested. But your code looks fine to me. You may try to use module.export instead of its alias exports , it may help:

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

But, as I said, your code looks fine to me as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM