Skip to content

Instantly share code, notes, and snippets.

@brycebaril
Last active June 23, 2016 03:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brycebaril/24d2dcb9c6741ebd12989c3e4aeb7856 to your computer and use it in GitHub Desktop.
Save brycebaril/24d2dcb9c6741ebd12989c3e4aeb7856 to your computer and use it in GitHub Desktop.
another user queue example, similar to how the Redis protocol works

requests come in e.g. /foo

replies come out upper-cased as /FOO

however, they are sent over to db.js to get upper-cased, and it replies two at once, concatenated with \n to delimit

when a reply comes back from db.js it sends both queued replies back to the HTTP clients at the same time, i.e. the first will wait until the second comes in.

// Wait until there are two queries, then reply to both, newline-concatenated
var net = require('net')
var s = net.createServer((c) => {
// for this test, assuming data won't be chunked here
var pending = []
function checkDone() {
if (pending.length == 2) {
c.write(pending.join('\n') + '\r\n')
pending = []
}
}
c.on('data', (chunk) => {
var message = chunk.slice(0, chunk.length - 2).toString().toUpperCase()
pending.push(message)
c.write('OK\r\n')
checkDone()
})
})
s.listen(7000)
bryce@x1c:~/ns$ curl http://localhost:8000/foo
/FOO
bryce@x1c:~/ns$ curl http://localhost:8000/bar
/BAR
var http = require('http')
var net = require('net')
var c = net.connect(7000)
c.on('data', checkReply)
var queued = []
function checkReply(chunk) {
// for this test, assuming data won't be chunked here
var message = chunk.slice(0, chunk.length - 2).toString()
if (message == 'OK') {
return
}
var replies = message.split('\n')
for (var i = 0; i < queued.length; i++) {
var fn = queued[i]
setImmediate(fn.bind(fn, replies[i]))
}
queued = []
}
function enqueue(data, cb) {
c.write(data + '\r\n')
queued.push(cb)
}
var s = http.createServer((req, res) => {
enqueue(req.url, (reply) => {
res.end(reply + '\n')
})
})
s.listen(8000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment