/
index.js
58 lines (51 loc) · 1.61 KB
/
index.js
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
var memoize = require('./lib/async-memoize')
var createMonitor = require('./lib/monitor')
var injectScript = require('./lib/inject-script')
var debug = require('debug')('quickreload')
var SseChannel = require('sse-channel')
var createClientScript = memoize(require('./lib/createClientScript'))
// Set up an interval that broadcasts server date every second
module.exports = function quickreload (options) {
options = options || {}
var channel = new SseChannel({jsonEncode: true})
createMonitor(options, function (err, monitor) {
if (err) {
throw err
}
monitor.on('change', function (ev) {
channel.send({
event: 'change',
data: {type: ev.type, file: ev.file}
})
})
})
const clientScriptOpts = {polyfill: options.polyfill}
// Just to warm the client script cache
createClientScript(clientScriptOpts, function noop () {})
return function (req, res, next) {
if (req.path === '/quickreload.js') {
debug('Serving /quickreload.js')
res.type('application/javascript')
createClientScript(clientScriptOpts, function (err, script) {
if (err) {
res.writeHead(500, {'Content-Type': 'text/plain'})
res.send('Internal server error: ' + err.message)
return
}
res.writeHead(200, {'Content-Type': 'text/javascript'})
res.end(script)
})
return
}
if (req.path === '/__quickreload_events') {
debug('Adding client')
channel.addClient(req, res)
return
}
if (options.inject !== false) {
debug('Injecting script')
injectScript(req, res)
}
next()
}
}