node.js静态资源访问

  • A+
所属分类:Web前端
摘要

 

 1 const http = require('http');  2 const url = require('url');  3 const path = require('path');  4 const fs = require('fs');  5 const mime=require('mime');  6   7   8 const app = http.createServer();  9 app.on('request',(req,res)=>{ 10  11     //获取用户请求路劲 12     let pathname=url.parse(req.url).pathname; 13  14     pathname = pathname== '/'? '/default.html':pathname; 15     //将用户的请求路径转换为实际的服务器路径 16     let realPath=path.join(__dirname,'public'+pathname); 17  18     // 当前请求文件类型 19     // console.log(mime.getType(realPath));  20     let type = mime.getType(realPath); 21     //读取文件 22     fs.readFile(realPath, (error,result)=>{ 23         if(error != null){ 24             res.writeHead(400, { 25                 'content-type': 'text/html;charset=utf8' 26             }); 27             res.end('文件读取失败'); 28             return; 29         } 30         res.writeHead(200,{ 31             'content-type':type 32         }) 33         res.end(result) 34     }) 35 }) 36  37 app.listen(3000); 38 console.log('服务器启动成功');