What should I be careful to avoid in order for my CoffeeScript code to run on both Node.js and javascript? The obvious answer is "don't use Node.js" functions, but I was wondering if there are other minor "gotchas" that would break porting the code between the two.
1 Answers
Assuming you don't rely on any APIs beyond the language itself (e.g. you don't use any functions other than setTimeout
/clearTimeout
and setInterval
/clearInterval
and those attached to Math
), there are just two things to worry about:
You can rely on newer JS features like
Array::forEach
andArray::indexOf
being around in Node, but not in the browser. CoffeeScript helps you avoid these two gotchas with thefor x in arr
andif x in arr
syntaxes, respectively.In the browser, the global object is
window
; in Node, the global object isglobal
, but you usually want to export things instead. So the usual solution, as demonstrated by Underscore.js and others, is to writeroot = this
at the top of your module and attach everything toroot
. In the outermost scope,this
points towindow
in browsers andexports
in Node.
I'm assuming here that you're defining your module in a single script. If not, you should look at a tool like sstephenson's stitch, which lets you write a set of modules that can require
each other in Node, then "stitch" them together for browsers.

- 76,828
- 33
- 160
- 196
-
1+1 for `root = this` -- despite the mighty Mr. Katz's [reassuring tone in this article](http://yehudakatz.com/2011/08/11/understanding-javascript-function-invocation-and-this/), if you do as Mr. Burnham says, your life will be much simpler in general. – fish2000 Mar 02 '12 at 03:10