0
点赞
收藏
分享

微信扫一扫

Nodejs学习笔记(三)--->利用HTTP模块 URl模块 Path模块 Fs模块创建一个静态WEB服务器

贵州谢高低 2022-02-06 阅读 20

Nodejs学习笔记(三)--->利用HTTP模块 URl模块 Path模块 Fs模块创建一个静态WEB服务器

第一步

app.js

const http = require('http');
const fs = require('fs');
const common=require('./module/common.js');
const path=require('path');
const url=require('url');
http.createServer(function (req, res) {
  //1、获取地址
    let pathname=url.parse(req.url).pathname;   
    //如果路径为'/',则让其跳转到index.html 
    pathname=pathname=='/'?'/index.html':pathname;
    //可以获取后缀名path.extname() 
    let extname=path.extname(pathname);
 //2、通过fs模块读取文件
    if(pathname!='/favicon.ico'){
        fs.readFile('./static'+pathname,(err,data)=>{
            if(err){                
                res.writeHead(404, {'Content-Type': 'text/html;charset="utf-8"'});  
                res.end('404这个页面不存在');               
            }
            let mime=common.getMime(extname);
            res.writeHead(200, {'Content-Type': ''+mime+';charset="utf-8"'});  
            res.end(data);            
        })
    }
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');

common.js

//定义一个函数,使其写入头的时候,针对不同文件,添加不同的Content-Type
exports.getMime = function (extname) {
  switch (extname) {
    case '.html':
      return 'text/html';
    case '.css':
      return 'text/css';
    case '.js':
      return 'text/javascript';
    default:
      return 'text/html';
  }
}

第二步

在上面的基础上对common.js做改造,以使其适用更对的文件类型

const fs = require('fs');

exports.getFileMime = function (extname) {
//注意,fs模块是异步的,所以外部想获取异步里的数据,不能直接获取,需封装成Promise,然后利用async和await让其变成同步
  return new Promise((resolve, reject) => {
  //mime.json是一个包含许多文件类型的json文件
    fs.readFile('./data/mime.json', (err, data) => {
      if (err) {
        console.log(err);
        reject(err);
        return;
      }
      let mimeObj = JSON.parse(data.toString());
      // console.log(mimeObj[extname]);
      resolve(mimeObj[extname]);
    })
  })
}

app.js

const http = require('http');
const fs = require('fs');
const common=require('./module/common.js');
const path=require('path');
const url=require('url');


http.createServer(function (req, res) {
  //1、获取地址
    let pathname=url.parse(req.url).pathname;    
    pathname=pathname=='/'?'/index.html':pathname;    
    let extname=path.extname(pathname);
 //2、通过fs模块读取文件
    if(pathname!='/favicon.ico'){
        fs.readFile('./static'+pathname,async (err,data)=>{
            if(err){                
                res.writeHead(404, {'Content-Type': 'text/html;charset="utf-8"'});  
                res.end('404这个页面不存在');               
            }
            let mime=await common.getFileMime(extname);
            res.writeHead(200, {'Content-Type': ''+mime+';charset="utf-8"'});  
            res.end(data);            
        })
    }   

}).listen(3000);

console.log('Server running at http://127.0.0.1:3000/');

第三步

针对第二步还可以进一步改进,利用readFileSync就可以实现异步变同步,使用了readFileSync,就不需要封装成Promise了
common.js

exports.getFileMime = function (extname) {
    var data=fs.readFileSync('./data/mime.json'); //同步方法
    let mimeObj=JSON.parse(data.toString());   
    return mimeObj[extname];    
}

app.js

const http = require('http');
const fs = require('fs');
const common=require('./module/common.js');
const path=require('path');
const url=require('url');


http.createServer(function (req, res) {
  //1、获取地址
    let pathname=url.parse(req.url).pathname;    
    pathname=pathname=='/'?'/index.html':pathname;    
    let extname=path.extname(pathname);
 //2、通过fs模块读取文件
    if(pathname!='/favicon.ico'){
        fs.readFile('./static'+pathname,(err,data)=>{
            if(err){                
                res.writeHead(404, {'Content-Type': 'text/html;charset="utf-8"'});  
                res.end('404这个页面不存在');               
            }
            let mime=common.getFileMime(extname);
            res.writeHead(200, {'Content-Type': ''+mime+';charset="utf-8"'});  
            res.end(data);            
        })
    }   
}).listen(3000);
console.log('Server running at http://127.0.0.1:3000/');

第四步

在第三步的基础上,封装静态WEB服务、 路由
将common.js重新命名为routers.js
routers.js

const fs = require('fs')
const path = require('path')
const url = require('url')


let getFileMime = async function (extname) {
  return new Promise((resolve, reject) => {
    fs.readFile('./data/mime.json', (err, data) => {
      if (err) {
        console.log(err)
        reject(err)
        return
      }
      let mimeObj = JSON.parse(data.toString())
      resolve(mimeObj[extname])
    })
  })
}

exports.static = async function (req, res, staticPath) {
  let pathname = url.parse(req.url).pathname
  pathname = pathname == '/' ? '/index.html' : pathname
  let extname = path.extname(pathname)

  if (pathname !== '/favicon.ico') {
    try {
      let data = fs.readFileSync('./' + staticPath + pathname);
      if (data) {
        let mime = await getFileMime(extname);
        res.writeHead(200, { 'Content-Type': '' + mime + ';charset="utf-8"' });
        res.end(data);
      }
    } catch (error) {
      //路由
      if (!extname) { //如果有请求地址有后缀名的话让静态web服务去处理 
        if (pathname == '/login') {
          res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
          res.end("执行登录");
        } else if (pathname == '/register') {
          res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
          res.end("执行注册");
        } else if (pathname == '/admin') {
          res.writeHead(200, { 'Content-Type': 'text/html;charset="utf-8"' });
          res.end("处理后的业务逻辑");
        } else {
          res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
          res.end("404");
        }
      }
    }
  }
}

app.js

const http = require('http')
const routes = require('./module/routers.js')

http.createServer(function (req, res) {
  routes.static(req, res, 'static')


}).listen(8081);

console.log('Server running at http://127.0.0.1:8081/');
举报

相关推荐

0 条评论