简体   繁体   中英

Where to save data in express.js app other than database?

I am showing a link on a page and I want to change that link, by using a form.

where should I save that link and retrieve to render the page other that a database?

*I think involving database for such a small task is not performance efficient.


what I can do is save it in a global variable as a string, so that I can access it and change it.

But is it a good practice to use global variable for such task in production?

I believe which approach you want to implement really depends on the scenario eg how frequently will the link be changed, how frequently will it be read etc. A couple of suggestions:

  1. If different user wants to see and update the same link without affecting others, you can use on client side stored cookies. Then you won't need a db but each user will manage their own link that no one else can access.
  2. You could use a file eg json or simple text file and use built in fs to read and write into that file. However in that case you would want to use sync operations to avoid concurrency issues eg const contents = fs.readFileSync('storage.txt', 'utf8');
  3. Of course you could store data in a string too, however if server was to go down, the link would not persist.

OK, now that we know that this is a change that you want to affect all users, then a global or preferably a module-level variable or a property on a module-shared object would be fine.

If you want this change to be persistent and survive a server restart, then you would need to write the change to disk somewhere and have code that reads that setting back in from disk when your server restarts. A simple way to do that might be to read/write it to a file in the JSON format. That gives you simple extensibility to also include other settings in that file.

Your admin form can then just update this variable and trigger a save to disk of all the current settings.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM