nodejs 学习(1) http与fs

var http=require("http"),
fs=require('fs');

var server=http.createServer(function(req,res){
    if("GET"==req.method && "/images"==req.url.substr(0,7) && ".jpg"==req.url.substr(-4)){
        fs.stat(__dirname+req.url,function(err,stat){//检测文件是否存在
            if(err||!stat.isFile()){
                res.writeHead(404);
                res.end('NOT FOUND');
                return;
            }
            serve(__dirname+req.url,"application/jpg");
        });
    }else if('GET'==req.method && '/'==req.url){
        serve(__dirname+'/index.html','text/html');
    }else{
        res.writeHead(404);
        res.end("NOT FOUND");
    }


    function serve(path,type){
        res.writeHead(200,{"Content-Type":"type"});
        fs.createReadStream(path).pipe(res);//将文件系统流接到http响应流中
    }
});


server.listen(3000);

 

posted on 2015-01-13 17:54  叫我钱了个浅  阅读(236)  评论(0编辑  收藏  举报

导航