首先还是先感谢github,感谢github上提供此段源码的作者。跟昨晚看的静态文件服务器来比今天的静态文件服务器稍微复杂些,可以学到很多新的东西。
仔细会发现这次的代码多了一个fs.stat函数和ReadStream对象的pipe函数,stat这个函数是用来获取文件信息。第一个参数是传入文件路径,第二个则是回调函数,回调函数的第二个参数stats的属性为文件的基本信息。pipe函数用于将这个可读流和destination目标可写流连接起来,传入这个流中的数据将会写入到destination流中。通过在必要时暂停和恢复流,来源流和目的流得以保持同步。

该静态文件服务器的改进点在于使用了Last-Modified和If-Modified-Since报文头,可以不必要给浏览器返回它已经存在的文件。顺便可以根据浏览器请求资源的压缩方式返回给资源进行gzip或者deflate压缩。

var PORT = 8000;
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"); var server = http.createServer(function(request, response) {
response.setHeader("Server", "Node/V5");
var pathname = url.parse(request.url).pathname;
console.log("url = " + pathname);
if (pathname.slice(-1) === "/") {
pathname = pathname + config.Welcome.file;
}
var realPath = __dirname + "/" + path.join("assets", path.normalize(pathname.replace(/\.\./g, "")));
console.log("realPath = " + realPath);
var pathHandle = function (realPath) {
fs.stat(realPath, function (err, stats) {
if (err) {
response.writeHead(404, "Not Found", {'Content-Type': 'text/plain'});
response.write("stats = " + stats);
response.write("This request URL " + pathname + " was not found on this server.");
response.end();
} else {
if (stats.isDirectory()) {
realPath = path.join(realPath, "/", config.Welcome.file);
pathHandle(realPath);
} 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();
//设置Last-Modified
//服务器给浏览器返回文件最后一次修改时间Last-Modified
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-Modified-Since报文头
//日期相同表示该资源没有变化则返回304
//告诉浏览器该资源你已经有了,不需要再请求了
if (request.headers[ifModifiedSince] && lastModified == request.headers[ifModifiedSince]) {
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(/\bgzip\b/)) {
response.writeHead(200, "Ok", {'Content-Encoding': 'gzip'});
raw.pipe(zlib.createGzip()).pipe(response);
} else if (matched && acceptEncoding.match(/\bdeflate\b/)) {
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("Server runing at port: " + PORT + ".");

Expires字段声明了一个网页或URL地址不再被浏览器缓存的时间,一旦超过了这个时间,浏览器都应该联系原始服务器。这里设置失效时间为1年。

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"
};

枚举各种资源的类型,可根据扩展名设置Content-Type。

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"
};

Node.js静态文件服务器的更多相关文章

  1. Node.js静态文件服务器实战[转]

    p.s. 在下面这篇文章的指导下,做了一个静态文件服务器,见:https://github.com/walkerwzy/node_static_server ==== 这是一篇阐述得比较详细的文章,从 ...

  2. 用http-server 创建node.js 静态服务器

    今天做一本书上的例子,结果代码不能正常运行,查询了一下,是语法过时了,书其实是新买的,出版不久. 过时代码如下 var connect=require('connect'); connect.crea ...

  3. Node.js静态页面展示例子2

    例程下载:https://files.cnblogs.com/files/xiandedanteng/nodejsStaticHtmlSample.rar 页面效果: Html页面代码(注意用文本编辑 ...

  4. 用node搭建静态文件服务器

    占个坑,写个node静态文件服务器

  5. hexo —— 简单、快速、强大的Node.js静态博客框架

    hexo是一款基于Node.js的静态博客框架.目前在GitHub上已有1375 star 和 219 fork. 特性 风一般的速度 Hexo基于Node.js,支持多进程,几百篇文章也可以秒生成. ...

  6. [Nodejs] node实现静态文件服务器

    node 静态文件处理 一般后端进行静态文件处理都是使用 Apache nginx 等静态 web 服务器,但是既然使用 node 了,就用 node 实现以下静态服务器吧. 之前弄了不少充满艺术的数 ...

  7. 使用node 做静态文件服务器

    # 1. 使用server-static 包 使用node可以非常快速的方法把指定目录共享出去 前提条件:安装了node,附带有npm 要托管的文件目录为 /root/www # 先创建一个目录用来存 ...

  8. 使用Node.js搭建静态资源服务器

    对于Node.js新手,搭建一个静态资源服务器是个不错的锻炼,从最简单的返回文件或错误开始,渐进增强,还可以逐步加深对http的理解.那就开始吧,让我们的双手沾满网络请求! Note: 当然在项目中如 ...

  9. 【干货分享】Node.js 中文学习资料和教程导航

    这篇文章来自 Github 上的一位开发者收集整理的 Node.js 中文学习资料和教程导航.Node 是一个服务器端 JavaScript 解释器,它将改变服务器应该如何工作的概念,它的目标是帮助程 ...

随机推荐

  1. C++/Java中继承关系引发的调用关系详解

    C++: 这里引用到了 http://blog.csdn.net/haoel/article/details/1948051/ 中的内容,还请提前阅读陈大神的这篇博客后在阅读本篇. 覆盖,实现多态的基 ...

  2. org.apache.catalina.util.DefaultAnnotationProcessor cannot be cast to org.ap解决方案

    非常可能是因为tomcat的lib文件夹jar包和项目的lib文件下的jar包冲突了 把项目下lib文件下和tomcat的jar的重复的全部删除. 注意,如果你是先建flex工程然后转成web形式的, ...

  3. python学习之路 一 :编程语言介绍

    本节重点 理解编程语言是什么? 大体明白,编程语言是如何与计算机底层通信的编程语言有哪些分类? 分别列举主流编程语言的特点 什么是编程,为什么要编程 一.什么是编程语言?为什么要编程? 编程:是个动词 ...

  4. 在eclipse上的hdfs的文件操作

    参考:http://dblab.xmu.edu.cn/blog/hadoop-build-project-using-eclipse/?tdsourcetag=s_pcqq_aiomsg:  http ...

  5. php中数组模拟队列、栈的函数以及数组指针操作

    1,数组指针,current表示当前指针,输出其指向的元素:next表示指针移动到下一个元素:prev指针移动到上一个元素:end表示指针移动到最后一个元素:reset表示指针移动到第一个元素: &l ...

  6. iOS开发之静态库.a 以及合并

    静态库和动态库 静态库和动态库的存在形式静态库: .a 和 .framework 动态库: .dylib 和 .framework 静态库和动态库在使用上的区别静态库:链接时,静态库会被完整地复制到可 ...

  7. Python 中当前位置以及目录文件遍历操作

    Python 中当前位置以及目录文件遍历操作 当前位置 print(os.path.dirname(__file__)) 其中 dirname 会选择目录(文件夹),"__file__&qu ...

  8. 正则表达式,sed简单用法

      一. 正则表达式 1. 常见的正则表达式字符 [] 匹配字符集 grep "bl[lo]g" oldboy.txt 表示字符‘l’或者‘o’都可匹配 * 重复前面字符任意次 g ...

  9. Squid代理服务器(三)——ACL访问控制

    一.ACL概念 Squid提供了强大的代理控制机制,通过合理设置ACL(Access Control List,访问控制列表)并进行限制,可以针对源地址.目标地址.访问的URL路径.访问的时间等各种条 ...

  10. dotnet --info

    [root@bogon ~]# dotnet --info.NET Command Line Tools (2.1.4) Product Information: Version: 2.1.4 Com ...