Node.js笔记(六)不使用页面模板渲染界面

来源:互联网 发布:java编程工具安卓 编辑:程序博客网 时间:2024/06/13 01:30

取这么一个标题,是因为实在想不起去什么名字
看网上的参考资料,ejs党和jade党势如水火Σ( ° △ °|||)︴
但对于我等新手,暂时不想分心去了解模板引擎,专心于html不是挺好的嘛

——————————————————————————
本文参考了Node.js实战的第二章,源码附在最后

首先看核心代码,目的是从缓存或者硬盘中读取html文件:

function serveStatic(response, cache, absPath) {  if (cache[absPath]) {//检查文件是否在缓存中    sendFile(response, absPath, cache[absPath]);//从内存中返回文件  } else {    fs.exists(absPath, function(exists) {//检查文件是否存在      if (exists) {        fs.readFile(absPath, function(err, data) {//从硬盘中返回文件          if (err) {            send404(response);          } else {            cache[absPath] = data;//加入缓存中            sendFile(response, absPath, data);//读取文件并返回          }        });      } else {        send404(response);      }    });  }}

send404和sendFile函数的实现

function send404(response) {  response.writeHead(404, {'Content-Type': 'text/plain'});  response.write('Error 404: resource not found.');  response.end();}function sendFile(response, filePath, fileContents) {  response.writeHead(    200,     {"content-type": mime.lookup(path.basename(filePath))}  );  response.end(fileContents);}

接下来是创建服务器

var server = http.createServer(function(request, response) {  var filePath = false;  if (request.url == '/') {    filePath = 'public/index2.html';  } else {    filePath = 'public' + request.url;  }  var absPath = './' + filePath;  serveStatic(response, cache, absPath);});

运行一下,应该是从csdn上扒下来的一篇博文

http://pan.baidu.com/s/1bnvYkSB

0 0
原创粉丝点击