您的位置:首页 > Web前端 > Node.js

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/




/* 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.');

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: