How do I dynamically update socket.io callbacks wi

2019-09-05 05:40发布

问题:

If I have a directory of files that say are in the following format:

module.exports =
  'add': (socket, data...) ->
    console.log 'words:add handler'.rainbow, data...
    socket.emit 'talkback', 'hahahha'

How do I include those files and when they are changed, update all connected socket.io clients to use the new callbacks.

If the filename is words.controller.coffee, I'd like the callback to be words:add.

So every time a new socket connects, how do I make each file that's already been loaded bind to the socket. And when a file changes, it should stop listening on that file, then start listening with the new binds.

回答1:

So this answer utilizes a library I wrote called loaddir. It walks through a directory and watches it and calls back with some defaults like basePath. In this case, for words.controller.coffee, the base path is words.controller

cs = require('coffee-script')
loaddir = require('loaddir')
handlers = {}
sockets = []

io.sockets.on 'connection', (socket) =>

  # keep track of currently connected sockets
  sockets.push socket
  socket.on 'disconnect', =>
    if -1 isnt (index = sockets.indexOf socket)
      sockets.splice index, 1
    console.log 'disconnected'

  # bind the currently loaded files ( we pass the socket along as well )
  _.each handlers, (event, event_name) =>
    socket.on event_name, -> event socket, arguments...

# Watches the directory for changes
loaddir

  path: ROOT + 'sockets' # this is our directory

  callback: ->

    # @basePath is provided by loaddir, in this case 'words.controller'
    module_name = @baseName.split('.')[0]

    # unbind the sockets that are currently connected
    _.each handlers, (event, nested_event_name) =>

      # only unbind for this file
      # nested_event_name == 'words:add'
      if nested_event_name.split(':')[0] == module_name
        _.each sockets, (socket) =>
          socket.removeListener nested_event_name, event
        delete handlers[nested_event_name]

    # Eval because we don't want to restart the server each time
    # @fileContents is provided by loaddir, we use coffeescript to compile it
    module_handlers = eval 'var module = {}; ' + (cs.compile @fileContents) + ' module.exports'

    # bind the currently connected sockets with this files events
    _.each module_handlers, (event, event_name) =>
      # event_name == 'add'
      handlers[module_name + ':' + event_name] = event
      _.each sockets, (socket) =>
        socket.on module_name + ':' + event_name, -> event socket, arguments...