Skip to content

Instantly share code, notes, and snippets.

Created March 3, 2013 19:42
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
What would you like to do?
{EventEmitter} = require 'events'
eventChannel = new EventEmitter()
eventChannel.on 'error', (args...) -> console.log "Event Channel received error:", args...
module.exports = eventChannel
{Server, Db, Timestamp} = require 'mongodb'
client = new Db 'local', new Server('localhost', 27017, {native_parser: true}), {w: 0}
eventChannel = config.require 'load/eventChannel'
getTimestamp = (date) ->
date ||= new Date()
time = Math.floor(date.getTime() / 1000)
new Timestamp 0, time
getDate = (timestamp) ->
new Date timestamp.high_ * 1000
mapOp =
n: 'noop'
i: 'insert'
u: 'update'
r: 'remove'
options = {} # raw
module.exports =
connect: (opts) ->
options.merge opts
watch: (collection) ->
# watch user model (err) ->
console.log 'Error connecting:', err if err
client.collection '', (err, oplog) ->
options =
tailable: true
tailableRetryInterval: 1000
numberOfRetries: 1000
currentTime = getTimestamp()
cursor = oplog.find {ts: {$gte: currentTime}}, options
stream =
stream.on 'data', (data) ->
if collection
return unless data.ns is collection
if options.raw
event = data
event =
timestamp: getDate data.ts
operation: mapOp[data.op] or data.op
namespace: data.ns
id: data.h.toString()
criteria: data.o2
data: data.o
eventChannel.emit 'change', event
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment