occasionally useful ruby, ubuntu, etc


CoffeeScript in Node.js

Here's a couple common development patterns I've come across in Node.JS+CoffeeScript.

Requiring Coffeescripts without compiling

So for the last couple weeks I've been doing Node.js development while using CoffeeScript, but I've been using `coffee -cwb .` in one console (which compiles, watches, and "bare bones"-style on the current directory) while running `node app.js` in another tab. This works okay, but whenever you add a new file you have to restart coffee, and it just seems...noisy. All these extra js files everywhere! Fortunately there's a better way, but it's not really documented.

require "./my_other_file.js" # compiled from "my_other_file.coffee"

require "coffee-script"
require "./my_other_file"

CoffeeScript registers the .coffee extension automatically. This means no more lingering js files.

Bootstrapping Coffeescripts

Another trick I've discovered applies to times that you have to execute a js file -- `node --debug myapp.js` comes to mind. Well, here you can just make a bootstrap.js file that contains two lines:

require "coffee-script"
require "./myapp"

Now you can `node --debug bootstrap.js` and everything works. Simple stuff.

Loading exports from a module efficiently

Thanks to Coffeescript's destructuring assignments capability, you don't have to write code that looks like this:

MyClass = require("./my_class").MyClass

you can simply write

{MyClass} = require("./my_class")

and it will do the same thing. You can even pull out multiple exports (i.e. {MyClass1,MyClass2}) at a time, though this doesn't come up for me that often.


Hope that was helpful. There are certainly a number of undocumented tricks that you discover when looking at other people's source code :)

p.s. sorry about the lack of source highlighting; don't feel like embedding gists in here. Code is pretty simple anyway!

Comments (2) Trackbacks (0)
  1. This helps me. Thank you.

  2. Excellent. While obvious in hindsight, the bootstrapping technique for invoking the node debugger was just what I needed.

Leave a comment

No trackbacks yet.