3

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.

Jonathan Dunlap
  • 2,581
  • 3
  • 19
  • 22

1 Answers1

5

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:

  1. You can rely on newer JS features like Array::forEach and Array::indexOf being around in Node, but not in the browser. CoffeeScript helps you avoid these two gotchas with the for x in arr and if x in arr syntaxes, respectively.

  2. In the browser, the global object is window; in Node, the global object is global, but you usually want to export things instead. So the usual solution, as demonstrated by Underscore.js and others, is to write root = this at the top of your module and attach everything to root. In the outermost scope, this points to window in browsers and exports 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.

Trevor Burnham
  • 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