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.
Share
Assuming you don’t rely on any APIs beyond the language itself (e.g. you don’t use any functions other than
setTimeout/clearTimeoutandsetInterval/clearIntervaland those attached toMath), there are just two things to worry about:You can rely on newer JS features like
Array::forEachandArray::indexOfbeing around in Node, but not in the browser. CoffeeScript helps you avoid these two gotchas with thefor x in arrandif x in arrsyntaxes, 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 = thisat the top of your module and attach everything toroot. In the outermost scope,thispoints towindowin browsers andexportsin 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
requireeach other in Node, then “stitch” them together for browsers.