Created
June 22, 2011 19:25
-
-
Save swdunlop/1040918 to your computer and use it in GitHub Desktop.
A Coffeescript Message Wall With Long Poll Properties in Node.JS and Express
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# our application server | |
app = require('express').createServer() | |
app.msgs = [] # a history of posted messages | |
app.defers = [] # a list of deferred responses | |
# / redirects to /q | |
app.get '/', (req, res) => | |
res.redirect('/q') | |
# /q[/<xxx>] query messages from the wall; may block for a protracted period | |
app.get '/q/:ofs?', (req, res) => | |
ofs = parseInt(req.params.ofs) || 0 | |
req.contentType 'text/plain' | |
if app.msgs.length > ofs | |
# send all messages on the wall to the user, starting from ofs | |
res.send app.msgs.slice(ofs).join('') | |
else | |
# waiting for the future; defer until it arrives | |
app.defers.push [ofs, res] | |
# /p?msg=<xxx> post a message to the wall | |
app.get '/p', (req, res) => | |
return if not req.query.msg | |
msg = req.query.msg + '\n' | |
app.msgs.push(msg) | |
# the future has arrived, notify all those who have deferred | |
defer.send msg for defer in app.defers | |
# now purge the deferrals | |
app.defers = [] | |
# listen to port 3000 for traffic. | |
app.listen( 3000 ) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is a straight port of my JavaScript wall to CoffeeScript; see https://gist.github.com/192d8b5e0f00a900cf88