Nodejs Express framework caching

前端 未结 4 1278
悲&欢浪女
悲&欢浪女 2020-12-07 19:31

I am using Nodejs and Express Js. Also I add NowJS to the Express Js to do some real-time stuffs.

In the configuration file I have

app.configure(\'pr         


        
相关标签:
4条回答
  • 2020-12-07 19:38

    The following code does the trick :

    var cacheTime = 86400000*7;     // 7 days
    
    app.use(express.static(__dirname + '/public',{ maxAge: cacheTime }));
    

    However my public directory contains CSS as well as html files.

    Is there a way i can cache css files only and not html.

    I tried the setting "no-cache" in meta tag for html file but it didn't work.

    0 讨论(0)
  • 2020-12-07 19:40

    EDIT: I was wrong, see eug's comment below

    Connect includes caching middleware: http://senchalabs.github.com/connect/middleware-staticCache.html

    so it should be as easy as

    app.use(express.cache(...));
    app.use(express.static(...));
    
    0 讨论(0)
  • 2020-12-07 19:56

    Express is built on Connect, and Connect provides the "static" middleware. Here's the code under the hood for the caching:

    if (!res.getHeader('Cache-Control')) res.setHeader('Cache-Control', 'public, max-age=' + (maxAge / 1000));
    

    You can find that code here:

    https://github.com/senchalabs/connect/blob/master/lib/middleware/static.js#L147

    So as you can see Express is sending a "Cache-Control" header to the browser, telling him to cache that file for a period. So this isn't a "load a file once and then always serve it to all clients", but more of a "tell each client to cache the file the first time he downloads it" (which means all the clients will have to download that file once before it's cached for them).

    0 讨论(0)
  • 2020-12-07 20:00

    The following code does the job:

    app.use(function (req, res, next) {
        if (req.url.match(/^\/(css|js|img|font)\/.+/)) {
            res.setHeader('Cache-Control', 'public, max-age=3600'); // cache header
        }
        next();
    });
    
    0 讨论(0)
提交回复
热议问题