-
-
Notifications
You must be signed in to change notification settings - Fork 156
/
Copy pathstart.js
102 lines (90 loc) · 2.55 KB
/
start.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
'use strict'
const connect = require('connect')
const serveStatic = require('serve-static')
const Renderer = require('docsify-server-renderer')
const util = require('../util')
const chalk = require('chalk')
const logger = require('../util/logger')
const LRU = require('lru-cache')
const defaultConfig = {
template: `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>My Doc</title>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/docsify/lib/themes/vue.css" title="vue">
</head>
<body>
<!--inject-app-->
<!--inject-config-->
<script src="//cdn.jsdelivr.net/npm/docsify/lib/docsify.min.js"></script>
</body>
</html>`
}
function loadConfig(config) {
try {
return require(util.cwd(config))
} catch (e) {
logger.error(`${e.message} in ${config}`)
process.exit(1)
}
}
module.exports = function (path, configFile, port) {
let config = defaultConfig
const pkg = util.pkg()
const ctx = util.cwd('.')
path = path || './'
if (configFile) {
config = loadConfig(configFile)
config.template = /\.html$/.test(config.template) ?
util.read(util.resolve(ctx, config.template)) :
defaultConfig.template
} else if (pkg.docsify) {
const tpl = pkg.docsify.template
config = pkg.docsify
config.template =
tpl && util.exists(util.resolve(ctx, tpl)) ?
util.read(tpl) :
defaultConfig.template
}
const renderer = new Renderer(Object.assign(defaultConfig, config))
const server = connect()
const cached = new LRU(config.maxAge || 0)
server.use(serveStatic(path))
server.use(function (req, res) {
serveStatic(path)(req, res, function () {
if (
/\.(jpg|jpeg|gif|png|svg|ico|mp4|webm|ogg|ogv|js|css|md)(?:\?v=[0-9.]+)?$/.test(
req.url
)
) {
res.writeHead(404)
res.end()
return
}
Promise.resolve(cached.get(req.url) || renderer.renderToString(req.url))
.then(function (html) {
cached.set(req.url)
res.end(html)
})
.catch(function (err) {
logger.error(err)
res.writeHead(404)
res.end()
})
})
})
server.listen(port || 4000)
const msg =
'\n' +
chalk.blue('[SSR]') +
' Serving ' +
chalk.green(`${path}`) +
' now.\n' +
'Listening at ' +
chalk.green(`http://localhost:${port}`) +
'\n'
console.log(msg)
}