如何在不重新启动服务器的情况下动态更新socket.io回调?

时间:2013-09-25 23:33:10

标签: node.js coffeescript socket.io

如果我有一个文件目录,说明采用以下格式:

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

如何包含这些文件以及更改时,请更新所有已连接的socket.io客户端以使用新的回调。

如果文件名是words.controller.coffee,我希望回调为words:add

因此,每次连接新套接字时,如何使已加载的每个文件都绑定到套接字。当文件发生变化时,它应该停止监听该文件,然后开始使用新的绑定进行监听。

1 个答案:

答案 0 :(得分:0)

所以这个答案使用了我写的名为loaddir的库。它遍历一个目录并观察它并使用basePath之类的默认值回调。在这种情况下,对于words.controller.coffee,基本路径为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...