Question

I am currently using a very simple piece of code to return requests for static content in node.js:

function staticRequest(req, res) {

    var toRetr = STATIC_DIR + req.params[0];

    if (fs.existsSync(toRetr)) {
        res.sendfile(toRetr);
    } else {
        res.status(404).send('Not found: ' + req.params[0]);
    }

};

I would like to use ETags to minimize redundant traffic between client and server.

  1. How can I implement or enable this?
  2. Should I implement an in-memory cache on the server side?
Was it helpful?

Solution 2

I resorted to using node's st module.

OTHER TIPS

I suggest something like this:

var _myEtags = {};

function staticRequest(req, res) {
  var toRetr = STATIC_DIR + req.params[0];
  if (_myEtags[req.get('ETag')]) {
    res.sendfile(toRetr);
  } else {
    if (fs.existsSync(toRetr)) {
       _myEtags[req.get('ETag')] = true;
       res.sendfile(toRetr);
    } else {
       res.status(404).send('Not found: ' + req.params[0]);
    }
  }
};

There are few node modules to serve static pages with caching.

https://github.com/cloudhead/node-static (Most popular on Github)

https://github.com/isaacs/st

https://github.com/divshot/superstatic

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top