-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmyserver.js
59 lines (54 loc) · 1.4 KB
/
myserver.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
/**
* 请求localhost:8081
* 响应列表
* <ul>
* <li>
* <a href = "/file?fileId=">文件名称</a>
* </li>
* <li>
* <a href = "/file?fileId">文件名称</a>
* </li>
* </ul>
*
* 点击超链接时,将超连接诶对应的文件内容,响应到页面是
* 显示
*/
const http = require("http");
const url = require("url");
const path = require("path");
const fs = require("fs");
http.createServer(httpManager).listen(8081);
function httpManager(req,res) {
var reqObj = url.parse(req.url, true);
var pathName = reqObj.pathname;
switch(pathName) {
case "/":
showIndex(res);
break;
case "/file":
showFile(reqObj,res);
break;
default:
res.end("error");
break;
}
}
var fileList = ["t1.txt", "t2.txt"];
function showIndex(res) {
var str = "<ul>";
for (var i = 0; i< fileList.length; i++) {
var liNode = "<li><a href='/file?fileId=" +i +"'>" +fileList[i] + "</a></li? "
str +=liNode;
}
str = str + "</ul>";
res.writeHead(200, {"Content-Type":"text/html"});
res.write(str);
res.end();
}
function showFile(reqObj,res) {
var fileId = reqObj.query.fileId;
var fileName = fileList[fileId];
var filePath = path.join(__dirname,"/" + fileName);
var fileContent = fs.readFileSync(filePath);
res.end(fileContent);
}