occasionally useful ruby, ubuntu, etc

30Oct/111

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.

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

After:
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.

Conclusion

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 (1) Trackbacks (0)
  1. This helps me. Thank you.


Leave a comment


No trackbacks yet.