zoukankan      html  css  js  c++  java
  • nodejs 之简单web服务器

    1、service.js

    var http=require('http');//引入http模块
    var fs=require('fs');//fs模块
    var path=require('path');  /*nodejs自带的模块*/  //path模块
    var url=require('url');//url模块
    var mimeModel=require('./model/getmime.js');
    
    http.createServer(function(req,res){
        //http://localhost:8001/news.html    /news.html
        var pathname=url.parse(req.url).pathname;
        console.log(pathname);
        if(pathname=='/'){
            pathname='/index.html'; /*默认加载的首页*/
        }
        //获取文件的后缀名
        var extname=path.extname(pathname);
        if(pathname!='/favicon.ico'){  /*过滤请求favicon.ico*/
    
            //文件操作获取 static下面的index.html
            fs.readFile('static/'+pathname,function(err,data){
                if(err){  /*么有这个文件*/
                    console.log('404');
                    fs.readFile('static/404.html',function(error,data404){
                        if(error){
                            console.log(error);
                        }
                        res.writeHead(404,{"Content-Type":"text/html;charset='utf-8'"});
                        res.write(data404);
                        res.end(); /*结束响应*/
                    })
                }else{ /*返回这个文件*/
    
                    var mime=mimeModel.getMime(extname);  /*获取文件类型*/
                    res.writeHead(200,{"Content-Type":""+mime+";charset='utf-8'"});
                    res.write(data);
                    res.end(); /*结束响应*/
                }
            })
        }
    }).listen(8001);

    2、getmime.js

    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';
        }
    }

      

  • 相关阅读:
    【原】 POJ 1308 Is It A Tree? 并查集树结构 解题报告
    终于决定投身Linux怀抱
    Inside the C++ Object Model
    Fedora 下 OpenCV 的安装
    sed 与 awk
    工具链接收藏
    [转] 计算机视觉领域稍微容易中的期刊
    QtCreator开发多文档编辑器(Project 1)
    Fedora 17: Grub Rescue
    做文档类的工作总是让我感到一些烦躁
  • 原文地址:https://www.cnblogs.com/ywjfx/p/10396942.html
Copyright © 2011-2022 走看看