本文实例讲述了node.js实现http服务器与浏览器之间的内容缓存操作。分享给大家供大家参考,具体如下:
一、缓存的作用
1、减少了数据传输,节约流量。
2、减少服务器压力,提高服务器性能。
3、加快客户端加载页面的速度。
二、缓存的分类
1、强制缓存,如果缓存有效,则不需要与服务器发生交互,直接使用缓存。
2、对比缓存,每次都需要与服务器发生交互,对缓存进行比较判断是否可以使用缓存。
三、通过使用 Last-Modified / If-Modified-Since 来进行缓存判断
1、Last-Modified 是服务器向客户端发送的头信息,用于告诉客户端资源的 最后修改时间,该信息浏览器会保存起来。
2、If-Modified-Since 是客户端向服务器发送的头信息,当客户端再次请求资源时,浏览器会带上该信息发送给服务器,服务器通过该信息来判断资源是否过期。
3、如果没有过期,则响应 304 表示 未更新,告诉浏览器使用保存的缓存。
4、如果过期了,则响应 200,返回最新的资源。
const http = require('http');const url = require('url');const path = require('path');const fs = require('fs');const util = require('util');const mime = require('mime');//创建http服务器并监听端口let server = http.createServer();server.listen(1234, '0.0.0.0', function () { console.log('开始监听');});function sendFile(req, res, filePath, stats) { //设置文件内容类型 res.setHeader('Content-Type', mime.getType(filePath)); //设置资源最后修改时间头信息 res.setHeader('Last-Modified', stats.ctime.toGMTString()); //通过管道将文件数据发送给客户端 fs.createReadStream(filePath).pipe(res);}server.on('request', function (req, res) { let {pathname} = url.parse(req.url, true); //获取文件真实路径 let filePath = path.join(__dirname, pathname); //判断文件是否存在 fs.stat(filePath, function (err, stats) { if (err) { return res.end(util.inspect(err)); } if (!stats.isFile()) { return res.end('is not file'); } //获取客户端请求的If-Modified-Since头信息 let ifModifiedSince = req.headers['if-modified-since']; if (ifModifiedSince) { //如果最后修改时间相同,说明该资源并未修改,直接响应 304,让浏览器从缓存中获取数据。 if (ifModifiedSince == stats.ctime.toGMTString()) { res.statusCode = 304; res.end(); } else { sendFile(req, res, filePath, stats); } } else { sendFile(req, res, filePath, stats); } });});
通过最后修改时间判断缓存是否可用,并不是很精确,有如下几个问题:
1、Last-Modified 只精确到秒,秒以下的时间修改,将无法准确判断。
2、文件最后修改时间变了,但 内容并没有发生改变。
新闻热点
疑难解答
图片精选