39

In ExpressJS for NodeJS, we can do the following:

app.use(express.static(__dirname + '/public'));

to serve all the static CSS, JS, and image files. My questions are these:

1) When we do that, does Express automatically cache the files in the server's memory or does it read from the hard disk every time one of the resources is served?

2) When we do that, does Express, using ETag by default, save the resources on the client's hard disk, or on the client's memory only?

1
  • 1
    1. Please note that even if express doesn't do this (I'm not sure), your operating system may actually do. Commented Aug 22, 2015 at 9:56

1 Answer 1

71
  1. The static middleware does no server-side caching. It lets you do two methods of client-side caching: ETag and Max-Age:

If the browser sees the ETag with the page, it will cache it. The next time the browser loads the page it checks for the ETag number changes. If the file is exactly the same, and so is its ETag - the server responds with an HTTP 304("not modified") status code instead of sending all the bytes again and saves a bunch of bandwidth. Etag is turned-on by default but you can turn it off like this:

app.use(express.static(myStaticPath, {
  etag: false
}))

Max-age is will set the max-age to some amount of time so the browser will only request that resource after one day has passed.

app.use(express.static(myStaticPath, {
  maxAge: '5000' // uses milliseconds per docs
}))

For more details you can read this article

  1. By default it's on the hard-drive, but someone can use something like this
5
  • So it tries to read from the server hard disk every time...How about the browser? Does the browser still remember the resource when the browser has been closed? Commented Aug 22, 2015 at 10:12
  • If the cache persists.
    – Dan D.
    Commented Aug 22, 2015 at 10:14
  • Dan D. ......I presume you are saying the resources are indeed stored in the client's hard disk... Under what conditions the cache persist and not persist? Commented Aug 22, 2015 at 10:19
  • @ChongLipPhang Did the user clear their browser history? Are they running in private/incognito mode (ie no cache)? Are they using dev tools with caching explicitly disabled? Have the cached files expired? It depends on the user. How their client handles caching is beyond the control of the server (except setting the expires length). Commented Dec 16, 2015 at 4:18
  • Haha, he ol' Ram Disk approach. I used that years ago to speed up a MSSQL database. If you take that approach, you'll need a watcher to synchronize between the ramdisk and persistent storage. Commented Dec 16, 2015 at 4:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.