当前位置: 首页 > 后端技术 > Node.js

nodenotes(3)-使用HTTP模块创建静态WEB服务器URl模块Path模块Fs模块

时间:2023-04-03 16:56:20 Node.js

目录识别responsehtml,css,jspath.extname(p)返回路径中文件的后缀名,即是,路径中的最后一个“.之后的部分”。如果路径不包含“.”或者路径只包含一个“.”和这个'。'是路径的第一个字符,此命令返回一个空字符串。index.html=>.htmlindex.jsexports.getMime=function(extname){switch(extname){case'.html':return'text/html';case'.css':return'text/css';case'.js':返回'text/javascript';默认值:返回“文本/html”;}}tets.jsvarhttp=require('http');varfs=require('fs')varpath=require('path');varmimeModel=require('./model/index.js');http.createServer(function(req,res){varpathname=req.url;if(pathname=='/'){pathname='/index.html'}varextname=path.extname(pathname);if(pathname!='/favicon.ico'){console.log(pathname)fs.readFile('static/'+pathname,function(err,data){if(err){console.log('404');//如果没有就返回404页面fs.readFile('static/404.html',function(error,data404){if(error){console.log(error)}res.writeHead(404,{'Content-Type':"text/html;charset='utf-8'"});res.write(data404)res.end()})}else{//根据不同类型的文件,head响应加载不同的文件格式varmime=mimeModel.getMime(extname);res.writeHead(200,{'Content-Type':""+mime+";charset='utf-8'"});res.write(data)res.end()}})}}).listen(8000);识别所有文件类型的响应mime.jsonindex2.jsexports.getMime=function(fs,extname){vardata=fs.readFileSync('./mime.json');varMimes=JSON.parse(data.toString());返回Mimes[分机名]||'text/html';}//Mimes['.html']=>text/htmltest3.jsvarhttp=require('http');varfs=require('fs')varpath=require('path');varurl=require('url');varmimeModel=require('./model/index2.js');http.createServer(function(req,res){varpathname=url.parse(req.url)。帕名字;if(pathname=='/'){pathname='/index.html'}//path.extname(p)返回路径中文件的后缀,即最后一个'.'之后的部分在路径中如果一个如果路径不包含“。”或者路径只包含一个“.”和这个'。'是路径的第一个字符,此命令返回一个空字符串。varextname=path.extname(路径名);if(pathname!='/favicon.ico'){console.log(pathname)fs.readFile('static/'+pathname,function(err,data){if(err){console.log('404');fs.readFile('static/404.html',function(error,data404){if(error){console.log(error)}res.writeHead(404,{'Content-Type':"text/html;charset='utf-8'"});res.write(data404)res.end()})}else{varmime=mimeModel.getMime(fs,extname);res.writeHead(200,{'Content-Type':""+mime+";charset='utf-8'"});res.write(data)res.end()}})}}).listen(8000);![图片上传中...]