Before we talk about caching, a few simple facts about HTTP status codes are essential:

  • The request was successful, and the response header or data body desired by the request is returned with this response. If this status code is displayed, it indicates the normal state
  • 304 Not Modified Mandatory cache
  • Of course, there are many other status codes, the above 200 and 304 are the focus of this article.

Why cache?

  1. Reduce response latency: When the server finds that the file has not been updated, it returns a 304 status code and tells the browser to read the cache instead of transferring the resource file.
  2. Reduced network bandwidth consumption: Reduced client bandwidth consumption when duplicates are reused; Customers can save on bandwidth costs, control the growth of bandwidth demand and make it easier to manage.
  3. If you set cache-control,expires, or something like that, you don’t need to send a request to the server again for a valid period of time. Instead, you need to read from the Cache (note that a status code of 200 in this case is also mandatory caching).

How to cache

You set the various caches by setting the HTTP headers

  1. Cache-Control
// Cache-control: no-cache/max-age=600let http = require('http')
let url = require('url')
let util = require('util')
let fs = require('mz/fs')
let stat = util.promisify(fs.stat);
let path = require('path');
let p = path.resolve(__dirname);
http.createServer(async function(req, res) {
    let {pathname} = url.parse(req.url);
    let realPath = path.join(p, pathname);
    console.log(realPath)
    try{
        let statObj = await fs.stat(realPath);
        console.log(statObj)
        res.setHeader('Cache-Control'.'max-age=10'Res.setheader (res.setheader)'Cache-Control'.'no-cache')
        res.setHeader('Content-Type',require('mime').getType(realPath)+'; charset=utf8')
       fs.createReadStream(realPath).pipe(res)
    }catch(e) {
        res.statusCode = 404;
        res.end('404')}}).listen(3000) we request a local file // index.html <! DOCTYPE html> <html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="Width = device - width, initial - scale = 1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    
    <img src="/agree.png"/ > < / body > < / HTML > / / in a browser open localhost: 3000 / index. The HTML / / can see the status code is 200, there are two kinds of the 200 is a kind of directly read cache / / 1. (from the memory cache) Cached in memory; (From disk cache) Cache in the hard disk //2. It is actually pulled from the serverCopy the code
  1. expires
//Expires:Sun, 22 Jul 2018 02:43:42 GMT // Note: If cache-control and Expires exist at the same time, cache-control has the final say'Expires', new Date(date.now () + 10*1000).togmtString ()), new Date(date.now () + 10*1000).togmtString ()Copy the code
  1. Last-Modified
To make comparison caching more obvious, we will force caching to be turned off in the following code: // res.setheader ('Cache-Control'.'no-cache'// The response header sets res.setheader ('Last-Modified'.statObj.ctime.togmtstring ()) // The request header will carry the req.headers['if-modified-since']

let http = require('http')
let url = require('url')
let util = require('util')
let fs = require('mz/fs')
let stat = util.promisify(fs.stat);
let path = require('path');
let p = path.resolve(__dirname);
http.createServer(async function(req, res) {
    let {pathname} = url.parse(req.url);
    let realPath = path.join(p, pathname);
    console.log(realPath)
    try{
        let statObj = await fs.stat(realPath);
        console.log(statObj)
        // res.setHeader('Cache-Control'.'max-age=10'Res.setheader (res.setheader (res.setheader))'Cache-Control'.'no-cache')
        res.setHeader('Content-Type',require('mime').getType(realPath)+'; charset=utf8')
        res.setHeader('Expires', new Date(date.now () + 10*1000).togmtString ()) // Force cachelet since = req.headers['if-modified-since'];
        if (since === statObj.ctime.togmtstring ()) {res.statusCode = 304 // Server cache res.end(); }else {
            res.setHeader('Last-Modified'.statObj.ctime.toGMTString())
            fs.createReadStream(realPath).pipe(res)
        }
    }catch(e) {
        res.statusCode = 404;
        res.end('404')}}), listen (3000) / / in a browser open localhost: 3000 / index. HTML refresh see is 304, we'll return a status code of 304, the browser will obediently to read from the cache files. // Let's change the index.html a little and see 200Copy the code
  1. Etag
// The response header is set to res.setheader ('Etag'.statObj.size.toString()); This is the size of the file // the request header will be req.headers['if-none-match'];
//
let http = require('http');
let util = require('util');
let fs = require('fs');
let stat = util.promisify(fs.stat);
let url = require('url');
let path = require('path');
letp = path.resolve(__dirname); // Compare content stat.size (not reliable) // First request Etag: content identifier // second request meif-none-match 
http.createServer(async function(req,res){
    let {pathname} = url.parse(req.url);
    let realPath = path.join(p,pathname);
    try{
        let statObj = await stat(realPath);
        console.log(realPath) 
        res.setHeader('Cache-Control'.'no-cache');
        let match = req.headers['if-none-match'];
        if(match){
            if(match === statObj.size.toString()){
                res.statusCode = 304;
                res.end();
            }else{
                res.setHeader('Etag'.statObj.size.toString()); fs.createReadStream(realPath).pipe(res); }}else{
            res.setHeader('Etag'.statObj.size.toString());
            fs.createReadStream(realPath).pipe(res);
        }
       
    }catch(e){
        res.statusCode = 404;
        res.end(`not found`);
    }
}).listen(3000);

Copy the code

The difference between the two caches

  1. Mandatory cache
  • Res.setheader (‘ cache-control ‘,’max-age=10’)
  • res.setHeader(‘Expires’, new Date(Date.now() + 10*1000).toGMTString())
  • The above two are decisive in the first way
  1. Compared to the cache
  • Last-modified —- if-modified-since
  • Etag —- if-none-match

The above is part of the content of web cache, welcome your valuable comments or suggestions, but also hope to help you get some knowledge from it, thank you for your attention!