SockJS+CoffeeScript+ Node.js组合使用指南

热3已有 9119 次阅读2012-06-22 10:49

I recently did a blog post on Socket.IO. Today I’ll go over an alternative called SockJS. According to the SockJS website: “SockJS is a browser JavaScript library that provides a WebSocket-like object. SockJS gives you a coherent, cross-browser, Javascript API which creates a low latency, full duplex, cross-domain communication channel between the browser and the web server”. Within the SockJS family there are server-side counterparts like the one for Node.js. As a side note – SockJS-Node is actually written in CoffeeScript

Note: I’m going to borrow from the examples provided and convert those to CoffeeScript.

Express creates the server and we call installHandlers passing in the app server so we can listen and answer any incoming requests on the echo path.

From the OS X Terminal I’m going to create a new folder and then install the dependencies (you can also call the package.json if you wish). If you have CoffeeScript installed globally then you can ignore the line that installs CoffeeScript. Make sure you have Node.js (with NPM) installed.

Take the above CoffeeScript that we converted and save it in the new folder. Call the file server.coffee

The example index.html file uses JavaScript inside of it. Typically, this is indeed how you will deploy a production app, however, did you know you can use CoffeeScript in the client side files as well? As a demo, I’ll show you how to do this. Please keep in mind that running CoffeeScript in the browser does make things a little slower and there are other side effects to be aware of according to the CoffeeScript website: “your inline scripts will run within a closure wrapper, so if you want to expose global variables or functions, attach them to the window object”

We will now take the script from the index.html file and convert it to use CoffeeScript: