-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
84 lines (66 loc) 路 2.06 KB
/
Copy pathserver.js
File metadata and controls
84 lines (66 loc) 路 2.06 KB
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
const http = require('http')
const fs = require('fs')
const path = require('path')
const url = require('url')
const parseArgs = require('./argument_parser.js')
const { isIgnoredPath, toRegexes } = require('./ignore_utils.js')
const {
portBanner,
helpOptions,
logAndExit,
packageVersion,
blue,
red
} = require('./console_utils.js')
const { partial } = require('./func_utils.js')
const { buildHtml } = require('./response_utils.js')
const ARGS = parseArgs(process.argv)
if (ARGS.HELP) logAndExit(helpOptions())
if (ARGS.VERSION) logAndExit(packageVersion())
const hostname = '127.0.0.1'
const port = ARGS.PORT || 3000
const LOCAL_DEV = ARGS.LOCAL_DEV
if (LOCAL_DEV) console.log('\nRunning in local development mode...\n')
const IGNORE_REGEXES = ARGS.IGNORE ? toRegexes(ARGS.IGNORE) : []
const shouldIgnore = partial(isIgnoredPath, IGNORE_REGEXES)
const CURRENT_PATH = '.'
const MODULE_PATH = LOCAL_DEV ? '.' : path.dirname(require.resolve('conssert'))
const server = http.createServer((req, res) => {
if (req.url === '/') {
res.writeHead(200, {'Content-type': 'text/html'})
res.end(buildHtml(CURRENT_PATH, MODULE_PATH, shouldIgnore))
return
}
const parsedUrl = url.parse(req.url)
const pathname = `.${parsedUrl.pathname}`
const ext = path.parse(pathname).ext
const mimeMap = {
'.ico': 'image/x-icon',
'.html': 'text/html',
'.js': 'text/javascript',
'.json': 'application/json',
'.css': 'text/css',
'.png': 'image/png',
'.jpg': 'image/jpeg',
'.svg': 'image/svg+xml',
}
const fileExists = (
fs.existsSync(pathname) &&
!fs.statSync(pathname).isDirectory()
)
if (fileExists) {
if (!ARGS.QUIET) {
console.log(pathname.endsWith('.test.js') ? blue(pathname) : pathname)
}
res.writeHead(200, {'Content-type': mimeMap[ext] || 'text/plain'})
res.end(fs.readFileSync(pathname))
return
} else {
console.log(`File Not Found: ${red(pathname)}`)
res.writeHead(404)
res.end(`File ${pathname} not found!`)
}
})
server.listen(port, hostname, () => {
console.log(portBanner(port))
})