node和express分别实现静态文件服务器
2016-01-23 20:50
796 查看
1、nodeJS版
使用express框架:
var http=require('http'); var fs=require('fs'); var url=require('url'); var path=require('path'); var PORT=9090; //添加MIME类型 var MIME_TYPE = { "css": "text/css", "gif": "image/gif", "html": "text/html", "ico": "image/x-icon", "jpeg": "image/jpeg", "jpg": "image/jpeg", "js": "text/javascript", "json": "application/json", "pdf": "application/pdf", "png": "image/png", "svg": "image/svg+xml", "swf": "application/x-shockwave-flash", "tiff": "image/tiff", "txt": "text/plain", "wav": "audio/x-wav", "wma": "audio/x-ms-wma", "wmv": "video/x-ms-wmv", "xml": "text/xml" }; var server = http.createServer(serverStatic); function serverStatic(req,res){ var filePath; if(req.url==="/"){ filePath = "index.html"; } else{ filePath = "./" + url.parse(req.url).pathname; } fs.exists(filePath,function(err){ if(!err){ send404(res); }else{ var ext = path.extname(filePath); ext = ext?ext.slice(1) : 'unknown'; var contentType = MIME_TYPE[ext] || "text/plain"; fs.readFile(filePath,function(err,data){ if(err){ res.end("<h1>500</h1>服务器内部错误!"); }else{ res.writeHead(200,{'content-type':contentType}); res.end(data.toString()); } });//fs.readfile } })//path.exists } server.listen(PORT); console.log("Server runing at port: " + PORT + "."); function send404(res){ res.end("<h1>404</h1><p>file not found</p>") }
使用express框架:
var express = require("express"); var app = express(); app.use("/",express.static(__dirname + "/public")); app.listen(3000);
相关文章推荐
- LeetCode:Remove Nth Node From End of List
- nodeJS环境
- Incorrect configuration: namenode address dfs.namenode.servicerpc-address or dfs.namenode.rpc-addres
- erlang node time ticket
- NodeJS - fs
- Express开发(一):Node.js、Express安装
- nodejs按业务逻辑组织路由器
- nodejs路由路径参数
- 使用CSLoader获取Node后再获取精灵失败
- nodejs的中间件
- leetcode222---Count Complete Tree Nodes(求完全二叉树节点数)
- 论Node在构建超媒体API中的作用
- [LeetCode24]Swap Nodes in Pairs
- 一张图告诉你,只会NodeJS还远远不够!
- NodeJS - NPM - Edge - Connect NodeJs and .Net
- 快慢指针-----Remove Nth Node From End of List
- Node.js中AES加密和其它语言不一致问题解决办法
- node.js乱码问题【WebStorm环境】
- NodeJs session中间件 及应用(简单的登录与登出)
- storm集成kafka报错【KeeperErrorCode = NoNode for /kafka/brokers/topics/test/partitions】