-
Notifications
You must be signed in to change notification settings - Fork 30
/
index.js
263 lines (239 loc) · 6.82 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
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
/**
* light-server
*
* Serve, watch, exucute commands and live-reload, all in one.
*
* Copyright (c) 2018 by Tianxiang Chen
*/
'use strict'
var morgan = require('morgan')
var connect = require('connect')
var serveStatic = require('serve-static')
var serveIndex = require('serve-index')
var injector = require('connect-injector')
var Gaze = require('gaze').Gaze
var LR = require('./livereload')
var spawn = require('child_process').spawn
var os = require('os').type()
function LightServer (options) {
if (!(this instanceof LightServer)) return new LightServer(options)
this.options = options
if (os === 'Windows_NT') {
this.shell = 'cmd'
this.firstParam = '/c'
} else {
this.shell = 'bash'
this.firstParam = '-c'
}
}
LightServer.prototype.writeLog = function (logLine) {
!this.options.quiet && console.log(logLine)
}
LightServer.prototype.start = function () {
var _this = this
if (!_this.options.serve && !_this.options.proxy) {
_this.watch()
return
}
var app = connect()
if (!this.options.quiet) {
app.use(function (req, res, next) {
if (req.url === '/favicon.ico') {
next()
} else {
morgan('dev')(req, res, next)
}
})
}
if (!_this.options.noReload) {
_this.lr = LR({
quiet: _this.options.quiet,
http2: _this.options.http2
})
app.use(_this.lr.middleFunc)
app.use(
injector(
function (req, res) {
return (
res.getHeader('content-type') &&
res.getHeader('content-type').indexOf('text/html') !== -1
)
},
function (data, req, res, callback) {
callback(
null,
data
.toString()
.replace(
'</body>',
'<script src="/__lightserver__/reload-client.js"></script></body>'
)
)
}
)
)
}
if (_this.options.serve) {
if (_this.options.proxy) {
var proxy = require('./proxy')
app.use(proxy(_this.options.proxy, _this.options.proxypaths).middleFunc)
}
if (_this.options.historyindex) {
var history = require('connect-history-api-fallback')
app.use(history({ index: _this.options.historyindex }))
}
app.use(
_this.options.servePrefix || '',
serveStatic(_this.options.serve, {
extensions: ['html'],
redirect: _this.options.serveRedirect === true,
fallthrough: true })
)
app.use(
_this.options.servePrefix || '',
serveIndex(_this.options.serve, { icons: true })
)
}
var server
if (_this.options.http2) {
var fs = require('fs')
var path = require('path')
server = require('spdy').createServer(
{
key: fs.readFileSync(path.join(__dirname, '/localhost.key')),
cert: fs.readFileSync(path.join(__dirname, '/localhost.crt'))
},
app
)
} else {
server = require('http').createServer(app)
}
server
.listen(_this.options.port, _this.options.bind, function () {
var listeningAddr =
(_this.options.http2 ? 'https://' : 'http://') +
(_this.options.bind || '0.0.0.0') +
':' +
_this.options.port
console.log('light-server is listening at ' + listeningAddr)
if (_this.options.serve) {
_this.writeLog(' serving static dir: ' + _this.options.serve)
if (_this.options.servePrefix) {
_this.writeLog(' using prefix ' + _this.options.servePrefix)
}
}
if (_this.options.proxy) {
_this.writeLog(
' when static file not found, proxy to ' + _this.options.proxy
)
_this.writeLog(
' if url path starts with "' + _this.options.proxypaths + '"'
)
}
_this.writeLog('')
if (_this.lr) {
_this.lr.startWS(server) // websocket shares same port with http
}
_this.watch()
if (_this.options.open) {
var opener = require('opener')
var openAddr = listeningAddr.replace('://0.0.0.0:', '://localhost:')
if (typeof _this.options.open === 'string') {
openAddr += _this.options.open
} else if (_this.options.servePrefix) {
openAddr += _this.options.servePrefix
}
opener(openAddr)
}
})
.on('error', function (err) {
if (err.errno === 'EADDRINUSE') {
console.log(
'## ERROR: port ' + _this.options.port + ' is already in use'
)
process.exit(2)
} else {
console.log(err)
}
})
}
LightServer.prototype.watch = function () {
var _this = this
_this.options.watchexps.forEach(function (we) {
var tokens = we.trim().split(/\s*#\s*/)
var filesToWatch = tokens[0].trim().split(/\s*,\s*/)
var commandToRun = tokens[1]
var reloadOption = tokens[2]
if (reloadOption !== 'reloadcss' && reloadOption !== 'no-reload') {
reloadOption = 'reload' // default value
}
if (commandToRun || _this.lr) {
_this.processWatchExp(filesToWatch, commandToRun, reloadOption)
} else {
console.log(
'## WARNING: Ignoring watch expression "' +
we +
'", because ' +
'it doesn\'t specify a command and live-reloading is disabled.'
)
}
})
}
LightServer.prototype.processWatchExp = function (
filesToWatch,
commandToRun,
reloadOption
) {
var _this = this
var gaze = new Gaze(filesToWatch, { interval: _this.options.interval })
// A file has been added/changed/deleted has occurred
gaze.on('all', function (event, filepath) {
if (gaze.executing) {
return
}
gaze.executing = true
_this.writeLog('* file: ' + filepath + ' was ' + event)
if (!commandToRun) {
if (_this.lr) {
_this.lr.trigger(reloadOption, _this.options.delay)
}
gaze.executing = false
return
}
console.log('## executing command: ' + commandToRun)
var start = new Date().getTime()
var p = spawn(_this.shell, [_this.firstParam, commandToRun], {
stdio: 'inherit'
})
p.on('close', function (code) {
if (code !== 0) {
console.log(
'## ERROR: command ' + commandToRun + ' exited with code ' + code
)
} else {
_this.writeLog(
'## command succeeded in ' + (new Date().getTime() - start) + 'ms'
)
if (_this.lr) {
_this.lr.trigger(reloadOption, _this.options.delay)
}
}
gaze.executing = false
})
})
if (filesToWatch.length) {
_this.writeLog(
'light-server is watching these files: ' + filesToWatch.join(', ')
)
_this.writeLog(' when file changes,')
if (commandToRun) {
_this.writeLog(' this command will be executed: ' + commandToRun)
}
if (_this.lr) {
_this.writeLog(
' this event will be sent to browser: ' + reloadOption + '\n'
)
}
}
}
module.exports = LightServer