forked from sirdesai22/create-nue
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.js
executable file
·47 lines (39 loc) · 1.18 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
// a super minimal web server to serve files on the current working directory
import { join, extname } from 'node:path'
import http from 'node:http'
import fs from 'node:fs'
import { networkInterfaces } from 'node:os'
export default function(opts={}) {
const { dir='www', port=8080 } = opts
const TYPES = {
html: 'text/html; charset=UTF-8',
js: 'application/javascript',
svg: 'image/svg+xml',
ico: 'image/x-icon',
png: 'image/png',
jpg: 'image/jpg',
css: 'text/css',
}
http.createServer(async (req, res) => {
let { url } = req
if (url.endsWith('/')) url += 'index.html'
let path = join(dir, url)
if (!fs.existsSync(path)) path = join(dir, '404.html')
const ext = extname(path).slice(1);
const head = { 'Content-Type': TYPES[ext] }
try {
res.writeHead(200, head)
fs.createReadStream(path).pipe(res)
} catch(e) {
res.writeHead(404, head)
res.end('')
}
}).listen(port)
// Network IP
const addr = networkInterfaces()?.eth0?.[0]?.address;
console.log(
process.isBun ? 'Bun' : 'Node',
`HTTP server at http://127.0.0.1:${port}/`,
addr ? `http://${addr}:${port}/` : ''
)
}