Converting to CoffeeScript run on Node.js

JavaScript is great language but it has those parts like inheritance and manipulations of data, that can slow developer down. The CoffeScript is one of the solutions. In addition, the CoffeeScript also adds the syntax sugar to write code faster and cleaner. It similar in a way how Groovy complements Java in many ways

Hello World Example

Lets create as following:

introduction = (x) ->
	"Hello " + x

console.log introduction("World")

Installing in Node

To run the CoffeeScript from node, it’s needs to be installed as following:

npm install -g coffee-script

This will install CoffeeSript globally

Running CoffeeScript

To run CoffeeScript script:


This compiles the into javascript and then Node interprets to execute it
To see how the CoffeeScript code looks in JavaScript, compile it as:

coffee -c

This will compile the coffee script into js file hello.js containing the JS code of the script. This works well for debugging not only for reviewing code but also running a debugger with breakpoints

Embed JavasCript in CoffeeScript

There may be times, you would like to run JS within the CoffeeScript code then:

`var introduction = function(name){
   return "Hello " + name;

console.log introduction("World")

As in the example, by adding (`) around the js code, you can embed the JS into CoffeeScript

Importing CoffeeScript in Node.js

Node.js uses ‘require’ to import modules and other JS code into the current code. If the module or code that need to be imported via the ‘require’ is CoffeeScript, then one way would be to compile the CoffeScript file. It would produce the JS file that will be included, however. To manually compile every single time the change is made in the CoffeeScript code, would not be productive. Solution is adding ‘require(“coffee-script”);’ at the top as following:

var should = require('should')
    , Domain = require('../index');

In this example, the ‘../index’ is referencing a ‘’ script. So by including ‘require(“coffee-script”)’ at the top, Node will compile the CoffeeScript for you before importing it.

Useful Links