26

I'm doing some tutorials and I'm writing everything in CoffeeScript. I then have to compile to JS then execute in node.js. Is there any way to do it directly?

Shamoon
  • 41,293
  • 91
  • 306
  • 570
  • See Trevor Burnham's answer to [this question](http://stackoverflow.com/questions/4679782/can-i-use-coffeescript-instead-of-js-for-node-js) – Ray Toal Sep 07 '11 at 16:43

2 Answers2

56

Yes you can.

coffee source.coffee -n

It will run Node directly without generating any .js files.

Reference

Update: Coffee now also supports --nodejs. The above does the same as

coffee source.coffee --nodejs

But yeah, -n is way shorter.

yujingz
  • 2,271
  • 1
  • 25
  • 29
  • Lol, my bad. Hope it helps though. I will take that comment back. – yujingz Mar 27 '13 at 08:15
  • Great; I assume the `-n` is just an example parameter to pass to the script invoked, correct? – mklement0 Aug 03 '13 at 02:57
  • @arvidkahl read the doc, seems --nodejs is just a prefix for passing in node options. will test it out tonight, thx – yujingz Dec 17 '13 at 18:59
  • @arvidkahl `--nodejs` works and it's able to do a lot more. But if you just want to simply execute, `-n' is way shorter :) – yujingz Jan 14 '14 at 20:26
  • @yujingz `-n` is a different, unrelated option. You don't need any command line options to just run a CoffeeScript file in Node. – Eric W Sep 17 '14 at 18:33
  • hey @EricW i understand that, maybe my previous statement is misleading. I just want to say `-n` is shorter not to mean its the abbreviation of `--nodejs` – yujingz Sep 17 '14 at 20:19
  • I think the options comes before the file, so this answer is essentially the same as `$ coffee source.coffee` – Pencilcheck Aug 30 '15 at 11:00
34

If you have npm, use it to install coffeescript from a node prompt: http://jashkenas.github.com/coffeescript/#installation

Then, from the node prompt, you can simply use the coffee command to execute:

coffee <yourcoffeescriptfile>.coffee

And, to just compile, pass the -c flag:

coffee -c <yourcoffeescriptfile>.coffee
driis
  • 161,458
  • 45
  • 265
  • 341
  • 8
    Also note that you can `require('./foo')` from a Node module to bring in `foo.coffee`, provided that you've already run `require('coffee-script')` (which you get for free when you run Node from the `coffee` command); it adds a hook to the `require` function. So mixing and matching `.coffee` and `.js` files in a Node app is very simple. – Trevor Burnham Sep 07 '11 at 18:08
  • Some more info on the use of `-c`: the compilation results are saved to a `.js` file with the same filename root in the same folder as the input file, unless `-o` is used to specify a different folder. Use `-p` to print the resulting JavaScript to `stdout` instead; run `coffee -h` to see all options. – mklement0 Aug 03 '13 at 03:02
  • The repo has been renamed to `coffeescript` so the link should be https://github.com/jashkenas/coffeescript/#installation – Linh Dam Mar 29 '16 at 12:23