Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does express.static() cache files in the memory?

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?

like image 592
Chong Lip Phang Avatar asked Aug 22 '15 09:08

Chong Lip Phang


People also ask

Are static files cached?

Static caching is when a browser requests a resource, the server providing the resource can tell the browser how long it should temporarily store or cache the resource. For any subsequent request for that resource, the browser uses its local copy, rather than going to the network to fetch it.

What are Express static files?

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.

What is static file caching?

While many forms of caching are available, static caching is a method for converting the page generated by a user's request into an HTML document to serve any subsequent requests to that same page.

What is the use of Express static?

static. Express looks up the files relative to the static directory, so the name of the static directory is not part of the URL. Express looks up the files in the order in which you set the static directories with the express. static middleware function.


1 Answers

  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
like image 76
Alexander Korzhykov Avatar answered Sep 28 '22 05:09

Alexander Korzhykov