cloudhead / node-static

rfc 2616 compliant HTTP static-file server module, with built-in caching.
MIT License
2.17k stars 245 forks source link

Better 'Cache-Control' syntax #117

Open pfumagalli opened 10 years ago

pfumagalli commented 10 years ago

Provide a way to support Cache-Control: no-cache or other custom caching informations. Here's a patch:

--- lib/node-static.js.orig 2014-03-04 14:13:43.000000000 +0900
+++ lib/node-static.js  2014-03-04 14:33:00.000000000 +0900
@@ -15,16 +15,26 @@

     this.root    = path.resolve(root || '.');
     this.options = options || {};
-    this.cache   = 3600;
+    this.cache   = 'max-age=3600';

     this.defaultHeaders  = {};
     this.options.headers = this.options.headers || {};

     if ('cache' in this.options) {
         if (typeof(this.options.cache) === 'number') {
+            if (this.options.cache > 0) {
+                this.cache = 'max-age=' + this.options.cache;
+            } else if (this.options.cache <= 0) {
+                this.cache = 'no-cache';
+            }
+        } else if (typeof(this.options.cache) === 'boolean') {
+            if (! this.options.cache) {
+                this.cache = 'no-cache';
+            }
+        } else if (this.options.cache.toLowerCase() == 'false') {
+            this.cache = 'no-cache';
+        } else if (this.options.cache.toLowerCase() != 'true') {
             this.cache = this.options.cache;
-        } else if (! this.options.cache) {
-            this.cache = false;
         }
     }

@@ -36,9 +46,7 @@

     this.defaultHeaders['server'] = this.serverInfo;

-    if (this.cache !== false) {
-        this.defaultHeaders['cache-control'] = 'max-age=' + this.cache;
-    }
+    this.defaultHeaders['Cache-Control'] = this.cache;

     for (var k in this.defaultHeaders) {
         this.options.headers[k] = this.options.headers[k] ||

Basically this is what it produces:

FagnerMartinsBrack commented 7 years ago

Alternatively, you can do this:

new static.Server(pathToServe, {
  headers: {
    'cache-control': 'no-cache'
  }
});

That will override the cache headers, and is a publicly documented API. I believe that's why nobody cares about this issue.