-
Notifications
You must be signed in to change notification settings - Fork 684
/
serve.js
executable file
·367 lines (285 loc) · 8.76 KB
/
serve.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
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
#!/usr/bin/env node
// Native
const path = require('path')
const {parse} = require('url')
// Packages
const {StringDecoder} = require('string_decoder')
const micro = require('micro')
const {red} = require('chalk')
const args = require('args')
const {compile} = require('handlebars')
const {isBinarySync} = require('istextorbinary')
const filesize = require('filesize')
const mime = require('mime-types')
const compress = require('micro-compress')
const fs = require('fs-promise')
const auth = require('basic-auth')
const stream = require('send')
const updateNotifier = require('update-notifier')
const {copy} = require('copy-paste')
// Ours
const pkg = require('../package')
args
.option('port', 'Port to listen on', process.env.PORT)
.option('cache', 'How long static files should be cached in the browser (seconds)', 3600)
.option('single', 'Serve single page apps with only one index.html')
.option('unzipped', 'Disable GZIP compression')
.option('ignore', 'Files and directories to ignore', '')
.option('auth', 'Serve behind basic auth')
.option(['o', 'cors'], 'Setup * CORS headers to allow requests from any origin', false)
const flags = args.parse(process.argv)
const directory = args.sub[0]
// Let user know if there's an update
// This isn't important when deployed to Now
if (!process.env.NOW) {
updateNotifier({pkg}).notify()
}
process.env.ASSET_DIR = '/' + Math.random().toString(36).substr(2, 10)
let current = process.cwd()
if (directory) {
current = path.resolve(process.cwd(), directory)
}
const isDir = async dir => {
let stats
try {
stats = await fs.stat(dir)
} catch (err) {
return false
}
if (stats.isDirectory()) {
return true
}
return false
}
const prepareView = () => {
let viewContent = false
const viewPath = path.normalize(path.join(__dirname, '/../views/index.hbs'))
try {
viewContent = fs.readFileSync(viewPath, 'utf8')
} catch (err) {
throw err
}
return compile(viewContent)
}
let ignoredFiles = [
'.DS_Store',
'.git/'
]
if (flags.ignore && flags.ignore.length > 0) {
ignoredFiles = ignoredFiles.concat(flags.ignore.split(','))
}
const renderDirectory = async dir => {
let files = []
const subPath = path.relative(current, dir)
if (!fs.existsSync(dir)) {
return false
}
try {
files = await fs.readdir(dir)
} catch (err) {
throw err
}
for (const file of files) {
const filePath = path.resolve(dir, file)
const index = files.indexOf(file)
const details = path.parse(filePath)
details.relative = path.join(subPath, details.base)
if (await isDir(filePath)) {
details.base += '/'
} else {
details.ext = details.ext.split('.')[1] || 'txt'
let fileStats
try {
fileStats = await fs.stat(filePath)
} catch (err) {
throw err
}
details.size = filesize(fileStats.size, {round: 0})
}
if (ignoredFiles.indexOf(details.base) > -1) {
delete files[index]
} else {
files[files.indexOf(file)] = details
}
}
const directory = path.join(path.basename(current), subPath, '/')
const pathParts = directory.split('/')
if (dir.indexOf(current + '/') > -1) {
const directoryPath = [...pathParts]
directoryPath.shift()
files.unshift({
base: '..',
relative: path.join(...directoryPath, '..')
})
}
const render = prepareView()
const paths = []
pathParts.pop()
for (const part in pathParts) {
if (!{}.hasOwnProperty.call(pathParts, part)) {
continue
}
let before = 0
const parents = []
while (before <= part) {
parents.push(pathParts[before])
before++
}
parents.shift()
paths.push({
name: pathParts[part],
url: parents.join('/')
})
}
const details = {
port: flags.port,
files,
assetDir: process.env.ASSET_DIR,
directory,
nodeVersion: process.version.split('v')[1],
paths
}
return render(details)
}
const handler = async (req, res) => {
if (flags.auth) {
const credentials = auth(req)
if (!process.env.SERVE_USER || !process.env.SERVE_PASSWORD) {
console.error(red('You are running serve with basic auth but did not set the SERVE_USER and SERVE_PASSWORD environment variables.'))
process.exit(1)
}
if (!credentials || credentials.name !== process.env.SERVE_USER || credentials.pass !== process.env.SERVE_PASSWORD) {
res.statusCode = 401
res.setHeader('WWW-Authenticate', 'Basic realm="User Visible Realm"')
return micro.send(res, 401, 'Access Denied')
}
}
const {pathname} = parse(req.url)
let related = path.parse(path.join(current, pathname))
if (related.dir.indexOf(process.env.ASSET_DIR) > -1) {
const relative = path.relative(process.env.ASSET_DIR, pathname)
related = path.parse(path.join(__dirname, '/../assets', relative))
}
related = decodeURIComponent(path.format(related))
let notFoundResponse = 'Not Found'
try {
const custom404Path = path.join(current, '/404.html')
notFoundResponse = await fs.readFile(custom404Path, 'utf-8')
} catch (err) {}
if (!fs.existsSync(related) && flags.single === undefined) {
return micro.send(res, 404, notFoundResponse)
}
// Check if file or directory path
if (await isDir(related)) {
let indexPath = path.join(related, '/index.html')
res.setHeader('Content-Type', mime.contentType(path.extname(indexPath)))
if (!fs.existsSync(indexPath)) {
// Try to render the current directory's content
const renderedDir = await renderDirectory(related)
// If it works, send the directory listing to the user
if (renderedDir) {
return micro.send(res, 200, renderedDir)
}
// And if it doesn't, see if it's a single page application
// If that's not true either, send an error
if (!flags.single) {
return micro.send(res, 404, notFoundResponse)
}
// But IF IT IS true, load the SPA's root index file
indexPath = path.join(current, '/index.html')
}
let indexContent
try {
indexContent = await fs.readFile(indexPath, 'utf8')
} catch (err) {
throw err
}
return micro.send(res, 200, indexContent)
}
if (!fs.existsSync(related) && flags.single) {
const indexPath = path.join(current, '/index.html')
let indexContent
try {
indexContent = await fs.readFile(indexPath, 'utf8')
} catch (err) {
return micro.send(res, 404, notFoundResponse)
}
return micro.send(res, 200, indexContent)
}
let body = 'Not able to load file!'
let stats
try {
body = await fs.readFile(related)
stats = await fs.stat(related)
} catch (err) {
if (err instanceof RangeError) {
return stream(req, related).pipe(res)
}
throw err
}
const binaryStat = isBinarySync(path.parse(related).base, body)
const getETag = s => '"' + s.dev + '-' + s.ino + '-' + s.mtime.getTime() + '"'
let requestDate = req.headers['if-modified-since']
let statusCode = 200
if (requestDate) {
requestDate = new Date(requestDate)
if (requestDate.getTime() === stats.mtime.getTime()) {
statusCode = 304
}
}
const defaultHeaders = {
'Cache-Control': 'public, max-age=' + flags.cache,
Pragma: 'public',
ETag: getETag(stats)
}
// Using same --cors behavior as in http-server:
// https://github.com/indexzero/http-server/blob/fed98f2dbb87f1ea7a793e48a1975c20c9e970fa/lib/http-server.js#L68
if (flags.cors) {
defaultHeaders['Access-Control-Allow-Origin'] = '*'
defaultHeaders['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Range'
}
for (const header in defaultHeaders) {
if (!{}.hasOwnProperty.call(defaultHeaders, header)) {
continue
}
res.setHeader(header, defaultHeaders[header])
}
if (binaryStat) {
res.statusCode = statusCode
res.end(body, 'binary')
} else {
const decoder = new StringDecoder('utf8')
const contentType = mime.contentType(path.extname(related)) || mime.contentType('text')
res.setHeader('Content-Type', contentType)
micro.send(res, statusCode, decoder.write(body))
}
}
const copyToClipboard = async text => {
try {
await copy(text)
return true
} catch (err) {
return false
}
}
const server = flags.unzipped ? micro(handler) : micro(compress(handler))
server.listen(flags.port, async () => {
const details = server.address()
const url = `http://localhost:${details.port}`
process.on('SIGINT', () => {
server.close()
process.exit(0)
})
if (!await isDir(current)) {
console.error(red('Specified directory doesn\'t exist!'))
process.exit(1)
}
if (!process.env.NOW) {
let message = `Running on ${url}`
const copied = await copyToClipboard(url)
if (copied) {
message = `${message} [copied to clipboard]`
}
console.log(message)
}
})