How would one make connect/express use non-expiring caching on a particular directory
Asked Answered
S

2

8

I'm working on an app that uses connect/express with node.js. It uses the "static" middleware like this:

var express = require("express");
var io = require("socket.io");

var app = express.createServer(
    express.static(__dirname + '/static')
);
app.listen(process.env.PORT || 8080);

var listener = io.listen(app);
var lobby = listener.of("/lobby");
lobby.on("connection", function (socket) {
    // etc etc etc
});

Within ./static, there's a folder, ./static/mp3, containing 88 audio files used by the app.

Though returning visitors have the files cached, it's driving me nuts that they still send 88 http requests to ask if their cached copies are out of date.

How can I enforce Expires or max-age caching, for only this folder?

Sabir answered 5/2, 2012 at 6:55 Comment(0)
S
23

Okay, the answer came easily once I realized how the connect "middleware" scheme works. My solution, which seems to be working great so far, was to insert my own middleware before static when calling express#createServer, like this:

var app = express.createServer(
    (function(req, res, next) {
        if(req.url.indexOf("/mp3/") === 0) {
            res.setHeader("Cache-Control", "public, max-age=345600"); // 4 days
            res.setHeader("Expires", new Date(Date.now() + 345600000).toUTCString());
        }
        return next();
    }),
    express.static(__dirname + '/static')
);
app.listen(process.env.PORT || 8080);
Sabir answered 7/2, 2012 at 20:0 Comment(0)
S
2

@brandon's answer was perfect, because I play with coffeescript, this is what I am using:

app.use (req, res, next) ->
  if req.url.indexOf "/js/" == 0 || req.url.indexOf "/img/" == 0
    res.setHeader "Cache-Control", "public, max-age=345600"
    res.setHeader "Expires", new Date(Date.now() + 345600000).toUTCString()
    next()

Cheers!

Sphenogram answered 1/5, 2013 at 9:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.