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.

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

+1 for root = this -- despite the mighty Mr. Katz's reassuring tone in this article, if you do as Mr. Burnham says, your life will be much simpler in general.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.