您的位置:首页 > 理论基础 > 计算机网络

nodejs系列学习:http请求html/css/js-----(二)

2016-07-01 17:22 399 查看
1、创建package.json文件

{
"name":"http_file",
"version":"0.0.2",
"discription":" http server",
"dependencies":{
"mime":"~1.2.7"
}

}


当前目录下执行,完成mime模块安装

npm  install


mime的js源码:在node_modules\mime下的mime.js文件看看就好

var path = require('path');
var fs = require('fs');

function Mime() {
// Map of extension -> mime type
this.types = Object.create(null);

// Map of mime type -> extension
this.extensions = Object.create(null);
}

/**
* Define mimetype -> extension mappings.  Each key is a mime-type that maps
* to an array of extensions associated with the type.  The first extension is
* used as the default extension for the type.
*
* e.g. mime.define({'audio/ogg', ['oga', 'ogg', 'spx']});
*
* @param map (Object) type definitions
*/
Mime.prototype.define = function (map) {
for (var type in map) {
var exts = map[type];

for (var i = 0; i < exts.length; i++) {
if (process.env.DEBUG_MIME && this.types[exts]) {
console.warn(this._loading.replace(/.*\//, ''), 'changes "' + exts[i] + '" extension type from ' +
this.types[exts] + ' to ' + type);
}

this.types[exts[i]] = type;
}

// Default extension is the first one we encounter
if (!this.extensions[type]) {
this.extensions[type] = exts[0];
}
}
};

/**
* Load an Apache2-style ".types" file
*
* This may be called multiple times (it's expected).  Where files declare
* overlapping types/extensions, the last file wins.
*
* @param file (String) path of file to load.
*/
Mime.prototype.load = function(file) {

this._loading = file;
// Read file and split into lines
var map = {},
content = fs.readFileSync(file, 'ascii'),
lines = content.split(/[\r\n]+/);

lines.forEach(function(line) {
// Clean up whitespace/comments, and split into fields
var fields = line.replace(/\s*#.*|^\s*|\s*$/g, '').split(/\s+/);
map[fields.shift()] = fields;
});

this.define(map);

this._loading = null;
};

/**
* Lookup a mime type based on extension
*/
Mime.prototype.lookup = function(path, fallback) {
var ext = path.replace(/.*[\.\/\\]/, '').toLowerCase();

return this.types[ext] || fallback || this.default_type;
};

/**
* Return file extension associated with a mime type
*/
Mime.prototype.extension = function(mimeType) {
var type = mimeType.match(/^\s*([^;\s]*)(?:;|\s|$)/)[1].toLowerCase();
return this.extensions[type];
};

// Default instance
var mime = new Mime();

// Load local copy of
// http://svn.apache.org/repos/asf/httpd/httpd/trunk/docs/conf/mime.types mime.load(path.join(__dirname, 'types/mime.types'));

// Load additional types from node.js community
mime.load(path.join(__dirname, 'types/node.types'));

// Default type
mime.default_type = mime.lookup('bin');

//
// Additional API specific to the default instance
//

mime.Mime = Mime;

/**
* Lookup a charset based on mime type.
*/
mime.charsets = {
lookup: function(mimeType, fallback) {
// Assume text types are utf8
return (/^text\//).test(mimeType) ? 'UTF-8' : fallback;
}
};

module.exports = mime;


2、创建server.js文件

var http=require('http');
var fs  =require('fs');
var path=require('path');
var mime=require('mime');

//缓存 减少io
var cache={};

//创建服务
var server=http.createServer(function(req,res){
var filepath=false;
switch (req.url){
case '/':
filepath='/public/index.html';
break;
default :
filepath=req.url;
break;
}
console.log(filepath);
var abspath='.'+filepath;
serverStatic(res,cache,abspath);
});
//开启服务
server.listen(9001,function(){
console.log('localhost:9001 server is started');
})

function rend404(response){
response.writeHead(404,{"Content-Type":'text/plain'});
response.write('ERROR:404 source not found.');
response.end();
}

//文件数据服务
function rendFile(response,filePath,fileContents){
log('render----'+filePath);
response.writeHead(200,{"Content-Type":mime.lookup(path.basename(filePath))});
response.end(fileContents);
}

//提供静态文件服务
function serverStatic(response,cache,absPath){
if(cache[absPath]){//检查文件是否在缓存中
log('在缓存中--'+absPath);
rendFile(response,absPath,cache[absPath]);
}else{//不在缓存中
fs.exists(absPath,function(exists){//检查文件是否存在
if(exists){//存在
fs.readFile(absPath,function(err,data){//读取文件
if(err){//读取失败
log('读取失败--'+absPath);
rend404(response);
}else{//读取成功
cache[absPath]=data;//添加数据到缓存
rendFile(response,absPath,data);
}
})
}else{//不存在
log('不存在--'+absPath);
rend404(response);
}
});

}

}

function log(msg){
console.log(msg);
}


通过 fs ; path ; mime ;完成文件读取路径及类型的操作,其实看完mine.js的源码可以发现require一个mime就够了。

3、”filepath=’/public/index.html’;”剩下就是在同级目录下创建资源文件css,img , js等。(有点小问题,中文路径)

4、跑起来

node  server.js


(三)说说module(模块,重用,module.exports,域)

提供下载:http://download.csdn.net/detail/zlin3007/9567033
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nodejs