-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
43 lines (33 loc) · 1016 Bytes
/
server.js
File metadata and controls
43 lines (33 loc) · 1016 Bytes
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
'use strict';
const http = require('http');
const url = require('url');
const fs = require('fs');
const mineType = require('./mineType.js');
const documentPath = '.';
const indexArr = ['/', '/index', '/index.html'];
const pathReg = new RegExp(/(.*)(\.[^\.]*)/);
const server = http.createServer((req, res) => {
const urlInfo = url.parse(req.url, true);
let reqPath = '';
if (indexArr.indexOf(urlInfo.path) > -1) {
reqPath = `${documentPath}/index.html`;
} else {
reqPath = `${documentPath}${urlInfo.path}`;
}
const pathArr = urlInfo.path.match(pathReg);
fs.readFile(reqPath, function(err, data) {
try {
res.writeHead(200, {
'content-type': pathArr ? `${mineType[pathArr[2]]};charset=utf-8` : 'charset=utf-8',
});
res.write(data);
res.end();
} catch (error) {
console.error('error', reqPath);
res.end();
}
});
});
server.listen(8080);
console.log('-----------------------------');
console.log('port:8080 server running');