I resorted to using node's st module.
Using ETags for static content in node
-
13-10-2022 - |
سؤال
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.
- How can I implement or enable this?
- Should I implement an in-memory cache on the server side?
المحلول 2
نصائح أخرى
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)
لا تنتمي إلى StackOverflow