-
Notifications
You must be signed in to change notification settings - Fork 87
/
livereload.coffee
96 lines (72 loc) · 2.33 KB
/
livereload.coffee
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
fs = require 'fs'
path = require 'path'
ws = require 'websocket-server'
version = '1.5'
defaultPort = 35729
defaultExts = [
'html', 'css', 'js', 'png', 'gif', 'jpg',
'php', 'php5', 'py', 'rb', 'erb'
]
defaultExclusions = ['.git/', '.svn/', '.hg/']
class Server
constructor: (@config) ->
@config ?= {}
@config.version ?= version
@config.port ?= defaultPort
@config.exts ?= []
@config.exclusions ?= []
@config.exts = @config.exts.concat defaultExts
@config.exclusions = @config.exclusions.concat defaultExclusions
@config.applyJSLive ?= false
@config.applyCSSLive ?= true
@server = ws.createServer()
@server.on 'connection', @onConnection.bind @
@server.on 'close', @onClose.bind @
listen: ->
@debug "LiveReload is waiting for browser to connect."
@server.listen @config.port
onConnection: (connection) ->
@debug "Browser connected."
connection.write "!!ver:#{@config.version}"
connection.on 'message', (message) =>
@debug "Browser URL: #{message}"
onClose: (connection) ->
@debug "Browser disconnected."
walkTree: (dirname, callback) ->
exts = @config.exts
exclusions = @config.exclusions
walk = (dirname) ->
fs.readdir dirname, (err, files) ->
if err then return callback err
files.forEach (file) ->
filename = path.join dirname, file
for exclusion in exclusions
return if filename.match exclusion
fs.stat filename, (err, stats) ->
if !err and stats.isDirectory()
walk filename
else
for ext in exts when filename.match "\.#{ext}$"
callback err, filename
break
walk dirname, callback
watch: (dirname) ->
@walkTree dirname, (err, filename) =>
throw err if err
fs.watchFile filename, (curr, prev) =>
if curr.mtime > prev.mtime
@refresh filename
refresh: (path) ->
@debug "Refresh: #{path}"
@server.broadcast JSON.stringify ['refresh',
path: path,
apply_js_live: @config.applyJSLive,
apply_css_live: @config.applyCSSLive
]
debug: (str) ->
if @config.debug
process.binding('stdio').writeError "#{str}\n"
exports.createServer = (args...) ->
server = new Server args...
server.listen()
server