-
Notifications
You must be signed in to change notification settings - Fork 0
/
http.js
69 lines (62 loc) · 1.9 KB
/
http.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
const http=require('http');
const url=require('url');
const path=require('path');
const fs=require('fs');
var pn='';
const hostLocal='localhost';
const hostIpv4=require('ipv4');
const port=8800;
http.createServer((req,res)=>{
let pathname=url.parse(req.url).pathname;
if(pathname.indexOf('.')==-1){
pathname+='/index.html';
}
let fileURL='./'+path.normalize('./build/'+pathname);
// let fileURL='./index.html';
console.log('地址为:'+fileURL)
// if(fileURL)
let extname=path.extname(pathname);
fs.readFile(fileURL,(Error,data)=>{
if(Error){
res.writeHead(404,{'Content-type':'text/html;charset=UTF8'});
res.end('404,资源没有找到!')
}
getMime(extname,(mime)=>{
res.writeHead(200,{'Content-type':mime});
res.end(data);
})
})
}).listen(port,hostLocal);
console.log(`we are listening:${hostLocal}:${port}`)
http.createServer((req,res)=>{
let pathname=url.parse(req.url).pathname;
if(pathname.indexOf('.')==-1){
pathname+='/index.html';
}
let fileURL='./'+path.normalize('./build/'+pathname);
// let fileURL='./index.html';
console.log('地址为:'+fileURL)
// if(fileURL)
let extname=path.extname(pathname);
fs.readFile(fileURL,(Error,data)=>{
if(Error){
res.writeHead(404,{'Content-type':'text/html;charset=UTF8'});
res.end('404,资源没有找到!')
}
getMime(extname,(mime)=>{
res.writeHead(200,{'Content-type':mime});
res.end(data);
})
})
}).listen(port,hostIpv4);
console.log(`You can also access us by IP:${hostIpv4}:${port}`)
function getMime(extname,callback){
fs.readFile('./config/mime.json',(err,data)=>{
if(err){
throw Error('sorry')
};
let mimeJson=JSON.parse(data);
let mimeType=mimeJson[extname]||'text/plain';
callback(mimeType)
})
}