Skip to content

Instantly share code, notes, and snippets.

@swdunlop

swdunlop/wall.js Secret

Created October 18, 2010 21:21
Show Gist options
  • Star 9 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save swdunlop/192d8b5e0f00a900cf88 to your computer and use it in GitHub Desktop.
Save swdunlop/192d8b5e0f00a900cf88 to your computer and use it in GitHub Desktop.
A Message Wall With Long Poll Properties in Node.JS and Express
// our application server
var app = require( 'express' ).createServer( )
// a list of messages scrawled on the wall
var msgs = []
// a list of deferred responses
var defers = []
// / redirects to /q
app.get( '/', function(req, res){
res.redirect( '/q' )
} )
// /q[/<xxx>] query messages from the wall; may block for a protracted period
app.get( '/q/:ofs?', function(req, res){
var ofs = parseInt( req.params.ofs ) || 0
res.contentType( 'text/plain' )
if( msgs.length > ofs ){
// send all messages on the wall to the user, starting from ofs
res.send( msgs.slice( ofs ).join( '\n' ) + '\n' )
}else{
// waiting for the future; defer until it arrives
defers.push( [ ofs, res ] )
}
} )
// /p?msg=<xxx> post a message to the wall
app.get( '/p', function( req, res ){
var ix, msg = req.query.msg
if( msg ) msgs.push( msg )
// the future has arrived, notify all those who have deferred
msg = msg + '\n'
for( ix in defers ){
defers[ix].send( msg )
}
// now purge the deferrals
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