occasionally useful ruby, ubuntu, etc

30Oct/112

Sharing session state in Node.js between your HTTP server and websockets server

At first, sharing your session state between your Node.js HTTP server and websockets server might seem difficult. However, if you're using Express and NowJS (or the technologies they're built on, Connect and Socket.IO, respectively), most of the work has already been done for you -- it's just a matter of connecting the right pieces together. An example follows, written in Coffeescript.

30Oct/112

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!

Filed under: coffeescript 2 Comments
16Jan/112

HydrateJS: Smarter Javascript Serialization

Finally, here it is: HydrateJS.

It's a library that helps you serialize proper Javascript objects, more than just hash-like objects like JSON.stringify can handle. Anyway, I put a lot of time into the documentation inside the library as well as on the Github Pages link, so check those out! There is also a full suite of specs.

For some of the technical challenges, see my previous post.

Let me know what you think in the comments, and if you're using it, feature requests, etc.