废话不多说,我们先来看看项目的文件结构,如下所示:
然后我们创建一个index.js的文件让他来做端口监听,代码如下所示:
var http = require('http'); var fs = require('fs'); var url = require('url'); FILE = "d:/node/code/http"; http.createServer(function(req,res){ res.writeHead(200,{"Content-Type":"text/html"}); //var data = fs.readFileSync('index.html'); urladdress = FILE+url.parse(req.url).pathname; //console.log(urladdress); //var data = fs.readFileSync(urladdress); //var data = fs.readFileSync(urladdress); //res.write(data); console.log(req.url); switch(req.url){ case '/': case "/index.html": if(url.parse(req.url).pathname != "/favicon.ico"){ var data = fs.readFileSync('index.html'); res.write(data); } break; case "/css/2.html": //console.log(__dirname+'/'+req.url); if(url.parse(req.url).pathname != "/favicon.ico"){ var data = fs.readFileSync(__dirname+'/'+req.url); //console.log(data); res.write(data); } break; case "/css/images/3.html": //console.log(__dirname+'/'+req.url); if(url.parse(req.url).pathname != "/favicon.ico"){ var data = fs.readFileSync(__dirname+'/'+req.url); //console.log(data); res.write(data); } break; } //res.write(data); res.end(); }).listen(4008);
然后测试,测试结果成功。。。。