用Node创建一个静态web服务器(读取文件)

创建服务器
  • 创建服务器的方法
    • http.cresteServer()
      //引入http模块
      const http = require('http');
      const { ESRCH } = require('constants');
      //创建web服务方法是http.creatServer(()=>()).listen(3000)
      
      http.createServer((req,res)=>{
         res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"});
         res.write('<head><meta charset="UTF-8"></head>')
         res.write('内容')
         res.end()
      }).listen(3000)
      console.log('http://127.0.0.1:3000')
      
    • 以上这个只能给客户端响应简单的数据
NodeJs创建一个web服务器(可以放置静态网站、下载web服务器上的文件)
  • 代码(文件类型手动写死)
    //NodeJs创建一个web服务器(可以放置静态网站、下载web服务器上的文件)
    //http://127.0.0.1:3000/index.html
    // 1.获取网站地址
    const http = require('http')
    const fs = require('fs')
    const path = require('path')
    const url = require('url')
    const common = require('./module/name.js')
    http.createServer((req, res) => {
        // res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"})
        //http://127.0.0.1:3000/index.html
        // 1.获取网站地址
        // let pathanme = req.url
        let pathanme = url.parse(req.url).pathname
        pathanme = pathanme == '/' ? '/index.html' : pathanme
        //path内置模块中有一个path.extname()方法获取后缀名
        let extanme = path.extname(pathanme)
        // console.log(extanme)
        //2. 通过fs模块读取文件
        if (pathanme != '/favicon.ico') {
            fs.readFile('./pack' + pathanme, (err, data) => {
                if (err) {
                    res.writeHead(404, { "Conten-type": 'text/html;charset="utf-8"' })
                    res.write('<head><meta charset="UTF-8"></head>')
                    res.end('页面不存在')
                } else {
                    let mime = common.getMime(extanme)
                    // res.writeHead(200,{"Conten-type":"text/html;charset='utf-8'"})
                    res.writeHead(200, { "Conten-type": '' + mime + ";charset='utf-8'" })
                    // res.write('<head><meta charset="UTF-8"></head>')
                    res.end(data)
                }
            })
        }
    }).listen(3000)
    console.log('http://127.0.0.1:3000')    
    
  • 自己定义的模块
    • module/name.js
    exports.getMime=function(e){
    	//e外部使用是传入的后缀名
        switch(e){
            case '.html':
                return 'text/html';
            case '.css':
                return 'text/css'
            case '.js':
                return 'text/javascript'
            default:
                return 'text/html';
        }
    }
    
- 创建web服务器(文件格式从json文件中读取)推荐(比较全面)(异步的方法)
  • 创建web服务器

    	//NodeJs创建一个web服务器(可以放置静态网站、下载web服务器上的文件)
    	//http://127.0.0.1:3000/index.html
    	// 1.获取网站地址
    	
    	const http = require('http')
    	const fs = require('fs')
    	const path = require('path')
    	const url = require('url')
    	const common = require('./module/name.js')
    	common.getMimes('.png')
    	http.createServer((req, res) => {
    	    // res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"})
    	    //http://127.0.0.1:3000/index.html
    	    // 1.获取网站地址
    	    // let pathanme = req.url
    	    let pathanme = url.parse(req.url).pathname
    	    pathanme = pathanme == '/' ? '/index.html' : pathanme
    	    //path内置模块中有一个path.extname()方法获取后缀名
    	    let extanme = path.extname(pathanme)
    	    // console.log(extanme)
    	    //2. 通过fs模块读取文件
    	    if (pathanme != '/favicon.ico') {
    	        fs.readFile('./pack' + pathanme, async (err, data) => {
    	            if (err) {
    	                res.writeHead(404, { "Conten-type": 'text/html;charset="utf-8"' })
    	                res.write('<head><meta charset="UTF-8"></head>')
    	                res.end('页面不存在')
    	            } else {
    	                // let mime = common.getMime(extanme)
    	                let mimes = await common.getMimes(extanme)
    	                
    	                // res.writeHead(200,{"Conten-type":"text/html;charset='utf-8'"})
    	                res.writeHead(200, { "Conten-type": '' + mimes + ";charset='utf-8'" })
    	                // res.write('<head><meta charset="UTF-8"></head>')
    	                res.end(data)
    	            }
    	        })
    	    }
    	}).listen(3000)
    	console.log('http://127.0.0.1:3000')    
    
  • 外部自定义模块/module/name.js

    //异步的
    const fs = require('fs')
    exports.getMimes =  function (a) {
        return new Promise((resolve,reject)=>{
            fs.readFile('data/Mime.json',(err,data)=>{
                if(err){
                    console.log(err)
                    reject(err)
                }else{
                     let site =  JSON.parse(data.toString())
                //    return site[a] 这是异步的,如果直接返回会有问题的(需要做异步处理)
                    // console.log(site[a])
                    resolve(site[a])
                }
            })
        })
        
    }
    // console.log(this.getMimes('.js'))
    // this.getMimes('.js')
    
  • 外部文件类型库的json文件Mime.json

    {
    	    ".ai": "application/postscript                 ",
    	    ".eps": "application/postscript                 ",
    	    ".exe": "application/octet-stream               ",
    	    ".doc": "application/vnd.ms-word                ",
    	    ".xls": "application/vnd.ms-excel               ",
    	    ".ppt": "application/vnd.ms-powerpoint          ",
    	    ".pps": "application/vnd.ms-powerpoint          ",
    	    ".pdf": "application/pdf                        ",
    	    ".xml": "application/xml                        ",
    	    ".odt": "application/vnd.oasis.opendocument.text",
    	    ".swf": "application/x-shockwave-flash          ",
    	    ".gz": "application/x-gzip                     ",
    	    ".tgz": "application/x-gzip                     ",
    	    ".bz": "application/x-bzip2                    ",
    	    ".bz2": "application/x-bzip2                    ",
    	    ".tbz": "application/x-bzip2                    ",
    	    ".zip": "application/zip                        ",
    	    ".rar": "application/x-rar                      ",
    	    ".tar": "application/x-tar                      ",
    	    ".7z ": "application/x-7z-compressed            ",
    	    ".txt": "text/plain               ",
    	    ".php": "text/x-php               ",
    	    ".html": "text/html                ",
    	    ".htm": "text/html                ",
    	    ".js": "text/javascript          ",
    	    ".css": "text/css                 ",
    	    ".rtf": "text/rtf                 ",
    	    ".rtfd": "text/rtfd                ",
    	    ".py": "text/x-python            ",
    	    ".java": "text/x-java-source       ",
    	    ".rb": "text/x-ruby              ",
    	    ".sh": "text/x-shellscript       ",
    	    ".pl": "text/x-perl              ",
    	    ".sql": "text/x-sql               ",
    	    ".bmp": "image/x-ms-bmp           ",
    	    ".jp": "image/jpeg               ",
    	    ".jpeg": "image/jpeg               ",
    	    ".gif": "image/gif                ",
    	    ".png": "image/png                ",
    	    ".tif": "image/tiff               ",
    	    ".tiff": "image/tiff               ",
    	    ".tga": "mage/x-targa             ",
    	    ".psd": "image/vnd.adobe.photoshop",
    	    ".mp3": "audio/mpeg               ",
    	    ".mid": "audio/midi               ",
    	    ".ogg": "audio/ogg                ",
    	    ".mp4a": "audio/mp4                ",
    	    ".wav": "audio/wav                ",
    	    ".wma": "audio/x-ms-wma           ",
    	    ".avi": "video/x-msvideo          ",
    	    ".dv": "video/x-dv               ",
    	    ".mp4": "video/mp4                ",
    	    ".mpeg": "video/mpeg               ",
    	    ".mpg": "video/mpeg               ",
    	    ".mov": "video/quicktime          ",
    	    ".wm": "video/x-ms-wmv           ",
    	    ".flv": "video/x-flv              ",
    	    ".mkv": "video/x-matroska         " 	} 	
       ```
        
    
创建web服务器(文件格式从json文件中读取)推荐(比较全面)(同步的方法)
  • 和上面的唯一的区别是一个是上面是异步的(需要用到async await),这里是同步的

  • 创建web服务器
    //NodeJs创建一个web服务器(可以放置静态网站、下载web服务器上的文件)
    //http://127.0.0.1:3000/index.html
    // 1.获取网站地址
    
    const http = require('http')
    const fs = require('fs')
    const path = require('path')
    const url = require('url')
    const common = require('./module/name.js')
    common.getMimes('.png')
    http.createServer((req, res) => {
        // res.writeHead(200,{"Content-type":"text/html;charset='utf-8'"})
        //http://127.0.0.1:3000/index.html
        // 1.获取网站地址
        // let pathanme = req.url
        let pathanme = url.parse(req.url).pathname
        pathanme = pathanme == '/' ? '/index.html' : pathanme
        //path内置模块中有一个path.extname()方法获取后缀名
        let extanme = path.extname(pathanme)
        // console.log(extanme)
        //2. 通过fs模块读取文件
        if (pathanme != '/favicon.ico') {
            fs.readFile('./pack' + pathanme, (err, data) => {
                if (err) {
                    res.writeHead(404, { "Conten-type": 'text/html;charset="utf-8"' })
                    res.write('<head><meta charset="UTF-8"></head>')
                    res.end('页面不存在')
                } else {
                    // let mime = common.getMime(extanme)
                    let mimes =  common.getMimes(extanme)
                    
                    // res.writeHead(200,{"Conten-type":"text/html;charset='utf-8'"})
                    res.writeHead(200, { "Conten-type": '' + mimes + ";charset='utf-8'" })
                    // res.write('<head><meta charset="UTF-8"></head>')
                    res.end(data)
                }
            })
        }
    }).listen(3000)
    console.log('http://127.0.0.1:3000')
    
  • 外部自定义模块/module/name.js
    //同步
    const fs = require('fs')
    exports.getMimes = function (a) {
        var data = fs.readFileSync('./data/Mime.json');//同步方法
        let site = JSON.parse(data.toString())
        return site[a]
    }
    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值