nodejs 通过回调函数获取异步函数中的数据

1、目录结构


2、mime.json

{ ".323":"text/h323" ,
  ".3gp":"video/3gpp" ,
  ".aab":"application/x-authoware-bin" ,
  ".aam":"application/x-authoware-map" ,
.......此处略去四百多行
  ".zip":"application/zip" ,
  ".json":"application/json"
}


3、getmimefromfile_callback.js

exports.getMime=function(fs,extname,callback){  /*获取后缀名的方法*/
  //.html
    console.log('1');
    fs.readFile('./mime.json',function(err,data){
        if(err){
            console.log('mime.json文件不存在');
            return false;
        }
        //console.log(data.toString());
        var Mimes=JSON.parse(data.toString());//把json字符串转换为json对象
        console.log('------------' + Mimes[extname]);
        console.log('2');
        var result = Mimes[extname] || 'text/html';
        //callback(Mimes[extname] || 'text/html');
        callback(result);
        //return Mimes[extname] || 'text/html';
    });
    console.log('3');
}

4、05service.js

//引入http模块
var http=require('http');
//fs模块
var fs=require('fs');
//path模块
var path=require('path');  /*nodejs自带的模块*/
//url模块
var url=require('url');
//引入扩展名的方法是在文件里面获取到的。
var mimeModel=require('./model/getmimefromfile_callback.js');
//console.log(mimeModel.getMime('.css'));   //获取文件类型
http.createServer(function(req,res){
    //http://localhost:8001/news.html    /news.html
    //http://localhost:8001/index.html    /index.html
    //css/dmb.bottom.css
    //xxx.json?214214124
    var pathname=url.parse(req.url).pathname;//使用url.parse()进行对请求的url进行过滤(去除不必要的请求参数,如?name=xx)
    console.log(pathname);
    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){//在static目录下寻找文件
            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(fs,extname,function(result02){//相当于callback
                    console.log('mime-------------' + result02);
                    res.writeHead(200,{"Content-Type":""+result02+";charset='utf-8'"});
                    res.write(data);
                    res.end(); /*结束响应*/
                });  /*获取文件类型*/
            }
        })
    }
}).listen(8002);

猜你喜欢

转载自blog.csdn.net/jiuweideqixu/article/details/86573443