纯原生nodejs启动静态html网页

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const http = require('http');
const fs = require('fs');
const path = require('path');
const cp = require('child_process');

const types = {
'.html':'text/html;charset=utf-8',
'.js':'application/javascript;charset=utf-8',
'.css':'text/css;charset=utf-8',
'.jpg':'image/*',
'.jped':'image/*',
'.png':'image/*',
'.webp':'image/*',
'.svg':'image/svg+xml',
}

const server = http.createServer((req, res) => {
try {
const filePath = path.join(__dirname, req.url === '/' ? 'index.html' : req.url);
const file = path.join(__dirname, req.url);
const data = fs.readFileSync(filePath);
res.writeHead(200, {'Content-Type': types[path.extname(filePath)]});
} catch (error) {}