Nodejs实现的一个静态服务器实例
作者:bea
参考cnodejs.org上面的静态服务器例子,写了下面的一个nodejs静态服务器例子,里面包含cache,压缩,贴代码如下: 代码如下: /** * 静态文件服务器测试例子 * User: xuwm * Date: 13-5-17 * Time: 上午8:38 * To change this template use File | Settings | File Templates. */ var port=3333; var http = req
参考cnodejs.org上面的静态服务器例子,写了下面的一个nodejs静态服务器例子,里面包含cache,压缩,贴代码如下:
代码如下:
/**
* 静态文件服务器测试例子
* User: xuwm
* Date: 13-5-17
* Time: 上午8:38
* To change this template use File | Settings | File Templates.
*/
var port=3333;
var http = require("http");
var url = require("url");
var fs = require("fs");
var path = require("path");
var mime = require("./mime").types;
var config = require("./config");
var zlib = require("zlib");
//创建http服务端
var server=http.createServer(function(request,response){
var obj= url.parse(request.url);
response.setHeader("Server","Node/V8");
console.log(obj);
var pathname=obj.pathname;
if(pathname.slice(-1)==="/"){
pathname=pathname+config.Welcome.file; //默认取当前默认下的index.html
}
var realPath = path.join("assets", path.normalize(pathname.replace(/../g, "")));
console.log(realPath) ;
var pathHandle=function(realPath){
//用fs.stat方法获取文件
fs.stat(realPath,function(err,stats){
if(err){
response.writeHead(404,"not found",{'Content-Type':'text/plain'});
response.write("the request "+realPath+" is not found");
response.end();
}else{
if(stats.isDirectory()){
}else{
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
var contentType = mime[ext] || "text/plain";
response.setHeader("Content-Type", contentType);
var lastModified = stats.mtime.toUTCString(); var ifModifiedSince = "If-Modified-Since".toLowerCase(); response.setHeader("Last-Modified", lastModified);
if (ext.match(config.Expires.fileMatch)) { var expires = new Date(); expires.setTime(expires.getTime() + config.Expires.maxAge * 1000); response.setHeader("Expires", expires.toUTCString()); response.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge); }
if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) { console.log("从浏览器cache里取") response.writeHead(304, "Not Modified"); response.end(); } else { var raw = fs.createReadStream(realPath); var acceptEncoding = request.headers['accept-encoding'] || ""; var matched = ext.match(config.Compress.match);
if (matched && acceptEncoding.match(/gzip/)) { response.writeHead(200, "Ok", {'Content-Encoding': 'gzip'}); raw.pipe(zlib.createGzip()).pipe(response); } else if (matched && acceptEncoding.match(/deflate/)) { response.writeHead(200, "Ok", {'Content-Encoding': 'deflate'}); raw.pipe(zlib.createDeflate()).pipe(response); } else { response.writeHead(200, "Ok"); raw.pipe(response); } } } } });
} pathHandle(realPath); }); server.listen(port); console.log("http server run in port:"+port);
首先需要在JS文件里创建一个assets的文件夹,里面放入你要浏览的静态文件,比如,index.html,demo.js等。
运行方式为:在命令行里切换到上面的JS的文件目录,然后输入 node JS文件名
浏览器内输入http://localhost:3333/就会看到效果。
--补上上面代码里缺少的两个模块
mime.js
代码如下:
exports.types = {
"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" };
config.js
代码如下:
exports.Expires = {
fileMatch: /^(gif|png|jpg|js|css)$/ig,
maxAge: 60 * 60 * 24 * 365
};
exports.Compress = { match: /css|js|html/ig };
exports.Welcome = { file: "index.html" };
有用 | 无用
代码如下:
/**
* 静态文件服务器测试例子
* User: xuwm
* Date: 13-5-17
* Time: 上午8:38
* To change this template use File | Settings | File Templates.
*/
var port=3333;
var http = require("http");
var url = require("url");
var fs = require("fs");
var path = require("path");
var mime = require("./mime").types;
var config = require("./config");
var zlib = require("zlib");
//创建http服务端
var server=http.createServer(function(request,response){
var obj= url.parse(request.url);
response.setHeader("Server","Node/V8");
console.log(obj);
var pathname=obj.pathname;
if(pathname.slice(-1)==="/"){
pathname=pathname+config.Welcome.file; //默认取当前默认下的index.html
}
var realPath = path.join("assets", path.normalize(pathname.replace(/../g, "")));
console.log(realPath) ;
var pathHandle=function(realPath){
//用fs.stat方法获取文件
fs.stat(realPath,function(err,stats){
if(err){
response.writeHead(404,"not found",{'Content-Type':'text/plain'});
response.write("the request "+realPath+" is not found");
response.end();
}else{
if(stats.isDirectory()){
}else{
var ext = path.extname(realPath);
ext = ext ? ext.slice(1) : 'unknown';
var contentType = mime[ext] || "text/plain";
response.setHeader("Content-Type", contentType);
var lastModified = stats.mtime.toUTCString(); var ifModifiedSince = "If-Modified-Since".toLowerCase(); response.setHeader("Last-Modified", lastModified);
if (ext.match(config.Expires.fileMatch)) { var expires = new Date(); expires.setTime(expires.getTime() + config.Expires.maxAge * 1000); response.setHeader("Expires", expires.toUTCString()); response.setHeader("Cache-Control", "max-age=" + config.Expires.maxAge); }
if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) { console.log("从浏览器cache里取") response.writeHead(304, "Not Modified"); response.end(); } else { var raw = fs.createReadStream(realPath); var acceptEncoding = request.headers['accept-encoding'] || ""; var matched = ext.match(config.Compress.match);
if (matched && acceptEncoding.match(/gzip/)) { response.writeHead(200, "Ok", {'Content-Encoding': 'gzip'}); raw.pipe(zlib.createGzip()).pipe(response); } else if (matched && acceptEncoding.match(/deflate/)) { response.writeHead(200, "Ok", {'Content-Encoding': 'deflate'}); raw.pipe(zlib.createDeflate()).pipe(response); } else { response.writeHead(200, "Ok"); raw.pipe(response); } } } } });
} pathHandle(realPath); }); server.listen(port); console.log("http server run in port:"+port);
首先需要在JS文件里创建一个assets的文件夹,里面放入你要浏览的静态文件,比如,index.html,demo.js等。
运行方式为:在命令行里切换到上面的JS的文件目录,然后输入 node JS文件名
浏览器内输入http://localhost:3333/就会看到效果。
--补上上面代码里缺少的两个模块
mime.js
代码如下:
exports.types = {
"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" };
config.js
代码如下:
exports.Expires = {
fileMatch: /^(gif|png|jpg|js|css)$/ig,
maxAge: 60 * 60 * 24 * 365
};
exports.Compress = { match: /css|js|html/ig };
exports.Welcome = { file: "index.html" };
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- 推荐9款炫酷的基于jquery的页面特效
- 2014 HTML5/CSS3热门动画特效TOP10
- 9款2014最热门jQuery实用特效推荐
- jQuery的图片滑块焦点图插件整理推荐
- 浅谈javascript回调函数
- javascript实现playfair和hill密码算法
- JS数组(Array)处理函数整理
- 浅谈JS日期(Date)处理函数
- AngularJS HTML编译器介绍
- AngularJS初始化过程分析(引导程序)
- 什么是 AngularJS?AngularJS简介
- AngularJS入门教程(二):AngularJS模板
- AngularJS入门教程(一):静态模板
- AngularJS入门教程(零):引导程序
- AngularJS入门教程之学习环境搭建
- AngularJS入门教程之Hello World!
- Nodejs实现多人同时在线移动鼠标的小游戏分享
- JavaScript中的Web worker多线程API研究
- JavaScript实现的一个日期格式化函数分享