http搭建服务器

 1 const http = require('http');
 2 const fs = require('fs');
 3 const path = require('path');
 4 const url = require('url');
 5 
 6 // 1. 创建服务器
 7 http.createServer((req, res) => {
 8     // 1.1 获取url的路径
 9     let pathUrl = url.parse(req.url);
10     let pathName = pathUrl.pathname;
11     // console.log(pathName);
12 
13     // 1.2 提取后缀
14     if(pathName.lastIndexOf('.') === -1){ // 没有
15        pathName += '/index.html';
16     }
17 
18     // 1.3 处理有后缀
19     let fileUrl = path.join(__dirname, pathName);
20     // console.log(fileUrl);
21 
22     // 取后缀
23     let extName = path.extname(fileUrl);
24 
25     // 1.4 读取文件
26     fs.readFile(fileUrl, (err, data)=>{
27        if(err){ // 没有找到页面
28            res.writeHead(404, {'content-type': 'text/html;charset=utf-8'});
29            res.end('<h1>404, 当前的页面不存在!</h1>');
30        }else { // 找到资源
31            getContentType(extName, (contentType)=>{
32                // console.log(contentType);
33                res.writeHead(200, {'content-type': contentType});
34                res.end(data);
35            });
36        }
37     });
38 }).listen(3000);
39 
40 
41 let getContentType = (extName, callback)=>{
42     // 读取文件
43     fs.readFile(path.join(__dirname, 'mime.json'), (err, data)=>{
44         if(err){
45             throw err;
46         }
47         let mineJson = JSON.parse(data);
48         let contentType = mineJson[extName] || 'text/plain';
49         callback && callback(contentType);
50     })
51 };


http://localhost:3000/static/index.html

猜你喜欢

转载自www.cnblogs.com/zhangzhengyang/p/11111883.html