//创建依赖模块
var http = require('http');
var url = require('url');
var fs = require('fs');
var server = http.createServer();
var htmlDir = __dirname + '/';
//console.log(htmlDir);
//处理url请求
function sendData(file,req,res) {
// console.log('file: ' + file);
fs.readFile(file,function(err,data) {
if(err) {
res.writeHead(404,{
'content-type':'text/html;charset=UTF8'
});
res.end('<h1>页面丢失</h1>');
}else{
res.writeHead(200,{
'content-type':'text/html;charset=UTF8'
});
res.end(data);
};
});
}
server.on('request',function(req,res) {
//console.log('收到客户端的请求了,路径是:' + req.url);
//response对象write方法
//获取url后面的路径
let urlStr = url.parse(req.url);
//判断url,返回响应数据
switch (urlStr.pathname) {
case '/':
sendData(htmlDir + 'index.html',req,res);
break;
case '/a':
sendData(htmlDir + 'a.html',req,res);
break;
case '/b':
sendData(htmlDir + 'b.html',req,res);
break;
default:
sendData(htmlDir + 'err.html',req,res);
break;
}
})
server.listen(3000,function() {
console.log('服务启动成功了');
})