node.js学习笔记5:作业(结合fs,get/post数据)

前面几篇内容按照node.js中不同模块的不同功能,分别记录了它们实现的方式。
这篇内容将前面几篇提到的功能结合起来,来实现一个简单的结合数据请求来实现文件读写的小页面。

我们可以尝试将前面提到的http模块创建服务器、fs模块读写文件和url模块处理get数据、querystring模块处理post数据一起结合起来做页面:

1
2
3
4
5
6
7
8
9
<form action="http://localhost:8080" method="get">
<input type="text" name="user"><br>
<input type="password" name="pass"><br>
<input type="submit" value="登录"><br><br>
</form>
<form action="http://localhost:8080" method="post">
<textarea name="content" cols="30" rows="10"></textarea><br>
<input type="submit" value="提交内容">
</form>

html页面

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
// 1. 引入需要的模块
const http=require("http");
const fs=require("fs");
const querystring = require("querystring");
const urlLib = require("url");

// 2. 创建服务器
http.createServer(function(req, res) {
// 判断是否为get数据
if(req.method == 'GET') {
let obj = urlLib.parse(req.url,true);
let GET = obj.query;
console.log(GET);
//判断是否为post数据
} else if (req.method == 'POST') {
let str = '';
req.on('data', data => str+= data);
req.on('end', () => {
let POST = querystring.parse(str);
console.log(POST);
// 如果POST内容不为空,即排除favicon,则将提交内容写入bbb.txt文件
if(Object.keys(POST).length !== 0) {
fs.writeFile('bbb.txt', POST.content, err => {
if(err !== null){
throw err;
}
});
}
})
}
}).listen(8080);

console.log("server running");

get提交数据时,终端输出结果

post提交数据时,终端输出结果

bbb.txt内容