-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
84 lines (74 loc) · 1.71 KB
/
server.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
/**
* basic server modules
*/
const http = require('http')
const ecstatic = require('ecstatic')
const HttpHashRouter = require('http-hash-router')
const filed = require('filed')
const fs = require('fs')
const ejs = require('ejs')
const pkg = require(process.cwd() + '/package.json')
const sendHtml = require('send-data/html')
const summary = require('server-summary')
/**
* Create Router
*/
const router = HttpHashRouter()
/**
* Default ecstatic options
*/
const options = {
root: process.cwd(),
handleError: false,
showDir: false,
cache: 0
}
/**
* Index
*/
let index = null
try {
index = fs.readFileSync(process.cwd() + '/index.html', 'utf-8')
} catch (e) {
index = ejs.render(fs.readFileSync(__dirname + '/index.ejs.html', 'utf-8'),pkg)
}
/**
* Default route serve index.html
*/
router.set('/', (req, res) => {
sendHtml(req, res, index)
})
/**
* serve client js files
*/
router.set('/js/:name', (req, res, data) => filed(`${__dirname}/client/js/${data.params.name}`).pipe(res))
/**
* serve markdown files or any other files in the project directory
*/
router.set('*', (req, res) => ecstatic(options)(req, res, function (err) {
if (/.md$/.test(req.url)) {
return filed(__dirname + '/client/404.md').pipe(res)
}
// other wise point back to basic html
sendHtml(req, res, index)
})
)
/**
* handle server requests
*/
const server = http.createServer(function (req, res) {
router(req, res, {}, (err) => {
sendHtml(req, res, index)
})
})
/**
* export listen command
*/
module.exports = port =>
server.listen(port || process.env.PORT || 3000, summary(server))
/**
* if no parent then listen
*/
if (!module.parent) {
server.listen(process.env.PORT || 3000, summary(server))
}