This repository was archived by the owner on May 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
43 lines (41 loc) · 1.42 KB
/
index.js
File metadata and controls
43 lines (41 loc) · 1.42 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
const http = require('http')
const fs = require('fs')
const url = require('url')
const path = require('path')
let server = http.createServer(function (request, response) {
//获取输入的url解析后的对象
let pathname = url.parse(request.url, true).pathname;
if (pathname == '/') {
pathname = '/index.html';
}
//static文件夹的绝对路径
let staticPath = path.resolve(__dirname, './');
//获取资源文件绝对路径
let filePath = path.join(staticPath, pathname);
console.log(filePath);
//异步读取file
fs.readFile(filePath, function (err, data) {
if (err) {
console.log(err);
// 如果找不到文件资源报错可以显示准备好的 404页面
let errPath = path.join(staticPath, '/404.html');
fs.readFile(errPath, (err, data404) => {
if (err) {
console.log('error');
response.write('404 Not Found');
response.end();
} else {
response.writeHead(404, { "Content-Type": "text/html;charset='utf-8'" });
response.write(data404);
response.end();
}
})
} else {
console.log('ok');
response.write(data);
response.end();
}
})
})
server.listen(8000)
console.log('visit http://localhost:8000')