The 2 minute guide to creating a new module in CoffeeScript for Node.js

Post to Twitter

Using modules in Node.js is an everyday task for most Node programmers. Today I’ll show you how to quickly create a class using CoffeeScript and to make it exportable into a Node.js project.


[ad name=”Google Adsense”]

I’ll assume you already have Node.js installed.

You need to use the NPM package coffee-script to do this example. I will be installing the CoffeeScript NPM package globally.

Warning: I’m using sudo here to avoid some permission issues on OS X. If your not comfortable using sudo that is reasonable given that your allowing something to have root access to your machine. There are other ways to install without using sudo – see the note below.

$ sudo npm install -g coffee-script

Note: If you don’t want to install CoffeeScript globally then do this instead (but make sure you are in the folder where you will be creating the projects files):

$ npm install coffee-script

Create two new files in a folder and call them app.coffee and hello.coffee. Inside of the hello.coffee file we will create a very simple class that can be exported.

module.exports = class Hello
  greet: () ->
    console.log 'hello'

In the app.coffee file we will simply create a new instance of the Hello class and call the greet method.

Hello = require("#{__dirname}/hello")

hello = new Hello()
hello.greet()

Run the app.coffee file like this:

$ coffee app.coffee

Expected results:

hello

Simple as that!

Just in case you’re curious the JavaScript code for the Hello class looks like this:

// Generated by CoffeeScript 1.3.3
(function() {
  var Hello;

  module.exports = Hello = (function() {

    function Hello() {}

    Hello.prototype.greet = function() {
      return console.log('hello');
    };

    return Hello;

  })();

}).call(this);

Post to Twitter

This entry was posted in CoffeeScript, JavaScript, Node.js, Open Source. Bookmark the permalink.