Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I ignore few static files in express static?

const express = require('express');

const app = express();

app.use('/app', express.static(path.resolve(__dirname, './app'), {
    maxage: '600s'
}))

app.listen(9292, function(err){
    if (err) console.log(err);
    console.log('listening at http:localhost:9292/app');
})

In my code have express static for serve static files. I want to add maxage header for few files not to all files.

Can I add maxage header for few files?

- app
    - js
      - app.js
    - css
       - app.css
    - index.html 

This is my app's static path. I want to add maxage header to all files instead of index.html

like image 290
Vasi Avatar asked Jul 13 '17 09:07

Vasi


People also ask

What is the use of static files in Express?

Static files are files that clients download as they are from the server. Create a new directory, public. Express, by default does not allow you to serve static files. You need to enable it using the following built-in middleware.

Should I use Express static?

You need express. static so your server can serve files that aren't being generated on the fly. It handles all the file loading and prevents path traversal attacks.

Can Express serve static files such as images?

To serve static files such as images, CSS files, and JavaScript files, use the express.

What are considered static files?

Static files are files that don't change when your application is running. These files do a lot to improve your application, but they aren't dynamically generated by your Python web server. In a typical web application, your most common static files will be the following types: Cascading Style Sheets, CSS.


1 Answers

Method 1

app.use(function (req, res, next) {
  console.log(req.url);
  if (req.url !== '/app/index.html') {
    res.header('Cache-Control', 'public, max-age=600s')
  }
  next();
});
app.use('/app', express.static(path.resolve(__dirname, './app')));

Method 2

You keep your js/css/images/etc. in different sub folders. For example, perhaps you keep everything in public/, except your html files are in public/templates/. In this case, you can split it by path:

var serveStatic = require('serve-static')

app.use('/templates', serveStatic(__dirname + '/public/templates'), { maxAge: 0 })
app.use(serveStatic(__dirname + '/public'), { maxAge: '1y' })

Method 3

Your files are all inter-mingled and you want to apply the 0 max age to all files that are text/html. In this case, you need to add a header setting filter:

var mime = require('mime-types')
var serveStatic = require('serve-static')

app.use(serveStatic(__dirname + '/public', {
  maxAge: '1y',
  setHeaders: function (res, path) {
    if (mime.lookup(path) === 'text/html') {
      res.setHeader('Cache-Control', 'public, max-age=0')
    }
  }
}))

method 2 and 3 are copied from github

like image 163
Fazal Rasel Avatar answered Nov 10 '22 01:11

Fazal Rasel