下面的例子主要包括文件的读、写、追加三个内容。
var http = require("http");
var url = require("url")
var querystring = require("querystring")
var fs = require("fs");
http.createServer(function (request, response) {
var objQuery = querystring.parse(url.parse(request.url).query);
if (objQuery.type == "read") {
fs.readFile("./file.txt", function (error, fileData) {
if (error) {
send(response, "<h1>read error</h1>");
} else {
send(response, "<h1>the read content:</h1>" + fileData);
}
});
}
else if (objQuery.type == "write") {
var writeString = "\n" + Date.now();
fs.writeFile("./file.txt", writeString, function (error) {
if (error) {
send(response, "<h1>write error</h1>");
} else {
send(response, "<h1>the write content:</h1>" + writeString);
}
});
}
else if (objQuery.type == "append") {
var appendString = "\n" + Date.now();
fs.appendFile("./file.txt", appendString, function (error) {
if (error) {
send(response, "<h1>append error</h1>");
} else {
send(response, "<h1>the append content:</h1>" + appendString);
}
});
} else {
send(response, "<h1>please input the right args:</h1>");
}
}).listen(8080, '192.168.33.98');
function send(response, content) {
response.writeHead(200, {
"content-type": "text/html"
});
response.write(content);
response.end();
}
在js文件的同一个目录下新建一个file.txt,内容为:abc(可以随便写的什么)。
在浏览器中输入:http://192.168.33.98:8080/?type=read,得到内容如下:
在浏览器中输入:http://192.168.33.98:8080/?type=write,得到内容如下:
此时,打开file.txt发现内容就是上面的那一串数字,这个是当前的格林尼治时间。
在浏览器中输入:http://192.168.33.98:8080/?type=append,得到内容如下:
再次打开file.txt,会发现多了一行如上数字。
原文:http://blog.csdn.net/xufeng0991/article/details/44464653