Can I use CoffeeScript instead of JS for node.js?


Question

What are my restrictions if I want to code node.js and use CoffeeScript? Can I do anything I'd be able to do in JS?

1
189
12/6/2012 12:09:22 PM

Accepted Answer

Yes, CoffeeScript simply compiles into pure JS, making it completely compatible with node.js.

To run CoffeeScripts on node, you can either:

  • Type coffee -c example.coffee to compile, followed by node example.js to run the compiled JS.
  • Simply type coffee example.coffee
175
1/13/2011 12:15:21 PM

Not only can you run CoffeeScript files directly in Node with

coffee source.coffee

you can also require them as if they were JavaScript files. For instance, if you have lib.coffee in a directory, you can write

require './lib'

from another CoffeeScript file in the same directory. (In order to do this from a JavaScript file, you'll have to add require 'coffee-script' at the top.) So, you never have to do compilation explicitly under Node, unless you're packaging your project for deployment with a tool like npm.

One caveat: In stack traces, the line numbers you'll see refer to the compiled JavaScript, even when you're running CoffeeScript directly (so you don't have access to the JavaScript). A lot of folks are trying to fix this, but it's a big challenge.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon