nodejs 创建静态文件服务器
2014-12-27 17:19
357 查看
nodejs创建静态文件服务器
要说 NodeJS 的静态服务器,前辈们已有诸多实践,并都付之笔墨与大家共享,尝试列举如下:
《Node.js静态文件服务器实战》朴灵大大的 Node 文章,非常详细,不可不说
http://www.infoq.com/cn/news/2011/11/tyq-nodejs-static-file-server
《完成静态服务器——Node.js摸石头系列之四》,还有其他关于 node 的文章
/article/5205814.html
《node.js入门—-静态文件服务器》,实现了 GZIP,这点要学习,,
http://www.jiangkunlun.com/2012/09/nodejs_%E9%9D%99%E6%80%81_%E6%9C%8D%E5%8A%A1%E5%99%A8/
要说 NodeJS 的静态服务器,前辈们已有诸多实践,并都付之笔墨与大家共享,尝试列举如下:
《Node.js静态文件服务器实战》朴灵大大的 Node 文章,非常详细,不可不说
http://www.infoq.com/cn/news/2011/11/tyq-nodejs-static-file-server
《完成静态服务器——Node.js摸石头系列之四》,还有其他关于 node 的文章
/article/5205814.html
《node.js入门—-静态文件服务器》,实现了 GZIP,这点要学习,,
http://www.jiangkunlun.com/2012/09/nodejs_%E9%9D%99%E6%80%81_%E6%9C%8D%E5%8A%A1%E5%99%A8/
/* Final Server */
var http = require('http'),
fs = require('fs'),
url = require('url'),
path = require('path'),
mime = require('./mime');
http.createServer(function(request, response){
//get path from request's url
var pathname = url.parse(request.url).pathname;
//map the path to server path
var absPath = __dirname + "/webroot" + pathname;
//test whether the file is exists first
path.exists(absPath, function(exists) {
if(exists) {
//二进制方式读取文件
fs.readFile(absPath,'binary',function(err, data) {
//our work is here
if(err) throw err;
//获取合适的 MIME 类型并写入 response 头信息
var ext = path.extname(pathname);
ext = ext ? ext.slice(1) : 'unknown';
console.log(ext);
var contentType = mime.types[ext] || "text/plain";
console.log(contentType);
response.writeHead(200,{'Content-Type':contentType});
//console.log(data);
//使用二进制模式写
response.write(data,'binary');
response.end();
});
} else {
//show 404
response.end('404 File not found.');
}
});
}).listen(3000);
console.log('Server start at port 3000.');
相关文章推荐
- nodejs使用nodejs创建简单的静态文件服务器
- nodejs使用nodejs创建简单的静态文件服务器
- nodejs使用nodejs创建简单的静态文件服务器
- 动态创建服务器控件,获取HTML输出(用于生成静态文件,简化页面,简化编程等)
- 动态创建服务器控件,获取HTML输出(用于生成静态文件,简化页面,简化编程等)
- nodeJS 静态文件服务器源码
- 用NodeJS打造你的静态文件服务器
- 用Nodejs搭建服务器访问html、css、JS等静态资源文件
- 用NodeJS打造你的静态文件服务器
- 一个简单的基于nodejs的静态文件服务器
- NodeJS VS Tomcat搭建高并发静态文件服务器
- 用NodeJS打造你的静态文件服务器
- nodejs生成的证书转换成cer文件便于在ios中使用--附Nodejs创建HTTPS服务器,并且生成证书
- 使用nodejs、Python写的一个简易HTTP静态文件服务器
- Node.js静态文件服务器实战(接触nodejs开发中比较实用的部分技巧,获益匪浅)
- 使用Nodejs快速搭建一个的本地静态文件服务器
- 动态创建服务器控件,获取HTML输出(用于生成静态文件,简化页面,简化编程等)
- nodejs 静态文件服务器
- [Nodejs]十分钟快速编写简单静态文件服务器
- 用NodeJS打造你的静态文件服务器