nodejs系列学习:http请求html/css/js-----(二)
2016-07-01 17:22
399 查看
1、创建package.json文件
当前目录下执行,完成mime模块安装
mime的js源码:在node_modules\mime下的mime.js文件看看就好
2、创建server.js文件
通过 fs ; path ; mime ;完成文件读取路径及类型的操作,其实看完mine.js的源码可以发现require一个mime就够了。
3、”filepath=’/public/index.html’;”剩下就是在同级目录下创建资源文件css,img , js等。(有点小问题,中文路径)
4、跑起来
(三)说说module(模块,重用,module.exports,域)
提供下载:http://download.csdn.net/detail/zlin3007/9567033
{ "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
相关文章推荐
- 使用ruby部署工具mina快速部署nodejs应用教程
- Google官方支持的NodeJS访问API,提供后台登录授权
- 浅谈Nodejs观察者模式
- nodejs教程之环境安装及运行
- nodejs中的fiber(纤程)库详解
- 基于NodeJS的前后端分离的思考与实践(五)多终端适配
- 基于NodeJS的前后端分离的思考与实践(二)模版探索
- 实例详解Nodejs 保存 payload 发送过来的文件
- 我的NodeJs学习小结(一)
- Node.js 应用跑得更快 10 个技巧
- nodejs中实现sleep功能实例
- Nodejs异步回调的优雅处理方法
- Windows系统下使用Sublime搭建nodejs环境
- nodejs实现获取某宝商品分类
- nodejs简单实现中英文翻译
- Node.js插件的正确编写方式
- 使用upstart把nodejs应用封装为系统服务实例
- NodeJS Web应用监听sock文件实例
- Nodejs学习笔记之测试驱动
- Nodejs学习笔记之Stream模块