2013-09-25 116 views
0

如果我有文件的目錄說是按以下格式:如何在不重新啓動服務器的情況下動態更新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

因此,每當新的套接字連接時,如何使每個已加載的文件都綁定到套接字。當一個文件改變時,它應該停止監聽該文件,然後開始用新的綁定進行監聽。

回答

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... 
相關問題