Home > Software design >  Returning a JSON file using Express
Returning a JSON file using Express

Time:12-02

I need to return a JSON file using Node and Express. I know how to do this, but there is a requirement mentioning that I need to "assume the file can change while the service runs." What do you think I should consider based on this statement?

Before sending it, I assume there should be some checks (if statements, etc.).

This is an open-ended question. I would like some direction from experienced devs.

CodePudding user response:

If you need to always be sure you're sending the latest version of the JSON file (and it could be changed while your server is running), then that just means that you can't cache it and can't load it with require() because that will cache it and you can't load it once at startup and keep the contents in memory (without manually checking yourself to see if the disk copy has changed).

As long as you're just using res.sendFile() to get the file from disk and send it, you should be OK as it will manage this for you. If the file extension is .json, it will even know to set the content-type to application/json for you.

res.sendFile() will use the date of the file in the OS for the lastModified header for purposes of browser caching so this should work properly as long as the OS last modified time is updated whenever the file changes (which would be the normal default behavior).

  • Related