Search code examples
javascriptnode.jsoopcoffeescript

Constants in Coffeescript and nodeJS


How should I keep constants? For example, I saw a lot of code in Github, where table names, rows, etc, are just hard coded in coffeescript class's method. how to proceed in such kind of constants, how to keep them? And how to keep constants, enums which are shared among modules. I guess I should create separate class only for exposing constants, right? And finally, What's what's the approach of keeping constants and enums among services in case of distributed app. For example, project can consist of several applications, which communicate to each other with sockets. Should I create another app, which only exposes constants? if so, what's the performance impact of this solution?


Solution

  • I would put application wide constants in their own module and export them as uppercase property names on module.exports.

    #constants.coffee
    module.exports =
      MAX_CONNECTIONS: 32
      SEASONS: ['WINTER', 'SPRING', 'SUMMER', 'FALL']
      ANSWER: 42
    

    No need for a class when you won't be creating many instances of it. You can also set them as module-level variables or class static members (@MAX_CONNECTIONS = 32) sign in a coffeescript class definition) as appropriate.