NodeJs-应用

接下来使用以上学过的url,http,fs等模块,创建一个静态web服务器。

web服务器一般指网站服务器,是指驻留于因特网撒花姑娘某种类型计算机的程序,可以向浏览器等web客户端提供文档,也可以放置往回走哪文件让全世界浏览,还可以放置数据文件,让全世界下载。目前最主流的web服务器有Apache、Nginxlls等。

Nodejs创建一个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.获取请求地址; 
  var pathname = url.parse(req.url).pathname; 

  //1.1 当初始请求是根目录/
  pathname = pathname == '/' ? '/index.html' : pathname;
  //获取后缀名paht.exthname()
  let extname=path.extname(pathname);
  //2.通过fs模块读取文件
  if (pathname != '/favicon.ico') {

    //刚开始我在服务器的最外层写了一行响应语句  res.end("hello world"),导致每次都访问不到文件,就几行代码找了半天,后来把它删了才正确访问到了。原因其实很简单,
    //因为readFile是一个异步执行,所以在等程序还没有读文件完毕的时候,下面这行代码直接把响应关闭了。
    fs.readFile('./static' + pathname, async(err, data) => {

      if (err) {
        res.writeHead(404, { 'Content-Type': 'text/html;charset="utf-8"' });
        res.end("这个页面不存在");
      }
      let mime=await common.getFileMime(extname);
      //返回成功响应头
      res.writeHead(200, { 'Content-Type': ''+mime+';charset="utf-8"' });
      //返回查询到的数据
      res.end(data);
    })
  }
}).listen(8081);

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

common.js

var fs=require('fs');
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';
    }
}
exports.getFileMime=function(extname){
    //因为fs.readeFile是异步操作,所以将其放在promise当中
    return new Promise((resolve,rejects)=>{
        //这里的mime.json文件中存放的是后缀名和类型匹配的内容
    fs.readFile('./data/mime.json',(err,data)=>{
         if(err){
             rejects(arr);
             return ;
         }
         let mimeobj=JSON.parse(data.toString());
         resolve(mimeobj[extname]);
    })
    })
}

static/index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="./index.css">
</head>
<body>
    <div id="main">我是index.html</div>    
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值