Write Module in Coffee Script for Node

There are a few ways to write a module in Coffee Script for Node. Below are two ways to contrast their usages. Notice how they share data @url and use function @find.

1.

user.coffee
-------------
class User
  constructor: (url) ->
    @url = url

  findOrCreate: (user, callback) ->
    @find user.username, (err, res) ->
    ...

  find: (username, callback) ->
    ...
module.exports.User = User

example.coffee
-------------
user = require('user')
User = new user.User('url')
...
User.findOrCreate u, (err, res) ->
  console.log @url
  ...

2.

user.coffee
-------------
init = (url) ->
  @url = url

find = (username, callback) ->
  ...
findOrCreate = (user, callback) ->
  console.log @url
  @find user.username, (err, res) ->
    ...

module.exports =
  init: init
  findOrCreate: findOrCreate

example.coffee
---------------
user = require 'user'
user.init 'url'
...
user.findOrCreate u, (err, res) ->
  ...

About rp8

Specialized in building sophisticated systems for trading & risks in commodity, exotics, commodity index & structured products. Specially interested in using open source stacks and cloud computing to build new generation of services and apps. Enjoy mountain biking & photography. github
This entry was posted in Node.js and tagged . Bookmark the permalink.