利用 HTTP 模块 URl 模块 PATH 模块 FS 模块创建一个 WEB 服务器 (6)

1Node.js 创建的第一个应用

//用 http 模块创建服务
http.createServer(function(req,res){
// 发送 HTTP 头部
// HTTP 状态值: 200 : OK
//设置 HTTP 头部,状态码是 200,文件类型是 html,字符集是 utf-8
res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"});
res.write('你好 nodejs');
res.write('我是第一个 nodejs 程序');
res.end(); /*结束响应*/
}).listen(8001);

2WEB 服务器介绍

  Web 服务器一般指网站服务器,是指驻留于因特网上某种类型计算机的程序,可以向浏览
器等 Web 客户端提供文档, 也可以放置网站文件,让全世界浏览;可以放置数据文件,让
全世界下载。目前最主流的三个 Web 服务器是 Apache Nginx IIS

3 创建一个简单的web服务器

目录结构

 `01 services1.js`代码

// 引入模块
var http = require('http');

// fs 模块
var fs =require('fs');

http.createServer(function (req, res) {
    //http://localhost:8001/news.html  /news.html
    //http://localhost:8001/index.html  /index.html
    //css/dmb.bottom.css

    var pathname =req.url;
    //路由分发
    if (pathname==='/'){
        pathname ='/index.html';
    }
    if (pathname!=='/favicon.ico'){
     console.log(pathname);
    fs.readFile('static'+pathname,function (err, data) {
        if (err){
            console.log('404');
        }else{
            res.writeHead(200,{"Content-Type":"text/html;charset='utf-8'"})
            res.write(data);
            res.end()
        }
    })
}
    console.log(pathname);
}).listen(8001);

4 调用解析后缀名的方法,构建content-type

`02 services2.js`

// 引入模块
var http = require('http');

// fs 模块
var fs =require('fs');

// path模块
var path = require('path');

// 自定义模块
var mimeModel =require('./model/getmime.js');

http.createServer(function (req, res) {
    //http://localhost:8001/news.html  /news.html
    //http://localhost:8001/index.html  /index.html
    //css/dmb.bottom.css

    var pathname =req.url;
    //路由分发
    if (pathname==='/'){
        pathname ='/index.html';
    }

    // 获取后缀名
    var extname = path.extname(pathname);

    if (pathname!=='/favicon.ico'){ /*过滤请求 favicon.ico*/
        //console.log(pathname);
        //文件操作获取 static 目录下的 index.html  文件
        fs.readFile('static'+pathname,function (err, data) {
            if (err){
                console.log('404');
                fs.readFile('static/404.html',function (err, data404) {
                    if (err){
                        console.log(err);
                    }
                    res.writeHead('404',{"Content-Type":"text/html;charset='utf-8'"});
                    res.write(data404);
                    res.end()
                })
            }else{//返回文件
                // 获取文件类型
                var mine = mimeModel.getMime(extname);
                res.writeHead(200,{"Content-Type":mine+";charset='utf-8'"});
                res.write(data);
                res.end()
            }
        })
    }
    console.log(pathname);
}).listen(8001);

`model/getmime.js`

/**
 * Created by Administrator on 2017/7/2 0002.
 */
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';
    }
};

5 读取文件属于异步执行过程,解说如下

getmimefromfile.js文件代码

 

exports.getMine = function (fs, extname) {
    //.html
    console.log('1');
    fs.readFile('mime.json',function (err, data) {
        console.log('fs.readFile:','2');
        if (err){
            console.log('../mine.josn文件不存在');
            console.log(err);
            return false
        }
        var Mines = JSON.parse(data.toString());
        return Mines[extname] || 'text/html' //默认返回'text/html'
    });
    console.log('3')
};

 

03 services.js 代码

// fs 模块
var fs =require('fs');
​
// path模块
var path = require('path');
​
// 自定义模块
var mimeModel =require('./model/getmimefromfile.js');
​
console.log("mimeModel.getMine(fs, '.html'):",mimeModel.getMine(fs, '.html'));

 

执行结果

 

原因分析:

1 fs.readFile 属于异步方法,顾程序执行到 fs.readFile ,不等待执行结果,就直接往下执行,最后返回undefiled.

 

解决办法: fs.readFile 改成 fs.readFileSync

 

exports.getMine = function (fs, extname) {
    //.html
    //把读取数据改成同步
    var data = fs.readFileSync('mime.json');
    //data.toString() 转换成json字符串
    var Mimes = JSON.parse(data.toString()); /*把json字符串转换成json对象*/
    return Mimes[extname] || 'text/html';
};

 6 使用文件动态构建 content-type

`04.services4.js`

// 引入模块
var http = require('http');

// fs 模块
var fs =require('fs');

// path模块
var path = require('path');

// 自定义模块
var mimeModel =require('./model/getmimefromfile.js');

http.createServer(function (req, res) {
    //http://localhost:8001/news.html  /news.html
    //http://localhost:8001/index.html  /index.html
    //css/dmb.bottom.css

    var pathname =req.url;
    //路由分发
    if (pathname==='/'){
        pathname ='/index.html';
    }

    // 获取后缀名
    var extname = path.extname(pathname);

    if (pathname!=='/favicon.ico'){ /*过滤请求 favicon.ico*/
        //console.log(pathname);
        //文件操作获取 static 目录下的 index.html  文件
        fs.readFile('static'+pathname,function (err, data) {
            if (err){
                console.log('404');
                fs.readFile('static/404.html',function (err, data404) {
                    if (err){
                        console.log(err);
                    }
                    res.writeHead('404',{"Content-Type":"text/html;charset='utf-8'"});
                    res.write(data404);
                    res.end()
                })
            }else{//返回文件
                // 获取文件类型
                var mine = mimeModel.getMine(fs,extname);
                res.writeHead(200,{"Content-Type":mine+";charset='utf-8'"});
                res.write(data);
                res.end()
            }
        })
    }
    console.log(pathname);
}).listen(8001);

`model/getmimefromfile.js`

exports.getMine = function (fs, extname) {
    //.html
    //把读取数据改成同步
    var data = fs.readFileSync('./mime.json');
    //data.toString() 转换成json字符串
    var Mimes = JSON.parse(data.toString()); /*把json字符串转换成json对象*/
    return Mimes[extname] || 'text/html';
};

 

猜你喜欢

转载自www.cnblogs.com/angle6-liu/p/11736682.html