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

本文介绍了一个简单的Node.js应用,该应用能够从缓存或硬盘读取HTML文件,并通过HTTP服务器进行提供。主要实现了文件缓存机制和服务端错误处理。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

取这么一个标题,是因为实在想不起去什么名字
看网上的参考资料,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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值