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);
hi,我的新博客地址:ysha.me !!