Node.js: How to write input values of a formular into a JSON file when the submit button is pressed?

前端 未结 1 823
半阙折子戏
半阙折子戏 2020-12-22 12:54

NEW: MORE SPECIFIC DESCRIPTION

I\'m programming a website with different products of different types. Each product has a detail page with a comment

相关标签:
1条回答
  • 2020-12-22 13:12

    Note: This answer was written before the question was rewritten: https://stackoverflow.com/posts/43213085/revisions

    This question is so general that it's hard to give you any specific answer. But if you want persistent data in your app then you should use a database.

    Some databases like Mongo, Postgres or Redis need to be run as standalone application either on the same or on a different server. Some embedded databases like SQLite don't need a standalone process and can be run directly in your application. There are multiple choices of databases and it's something that you have to choose yourself for your particular case. But you should choose some database to store the data.

    It's not that it is impossible to write to JSON files on updates and then read those files as needed, but the amount of work that you'd have to do to synchronize the access to the data so that no two requests to write happen at the same time and no read happens while a write is in progress, all that without accidentally blocking the event loop in the process and handling multiple requests concurrently, is something greatly more difficult than just using any database as intended.

    Some databases like Mongo will let you store any JSON documents (actually it stores BSON but for the user it's just like JSON). Using a document database like Mongo or CouchDB will be most similar to having JSON files but using a relational database could work as well. Pretty much every persistent data is kept in databases. If you can write your own database that stores data in JSON files then by all means do it if you need, but if you can't then just use the right tool for the job.

    That having been said, if you still insist on reading and writing JSON files, here's what to do:

    To write data as JSON into files, you will need to use JSON.stringify() and fs.writeFile().

    To read JSON data from files, you will need to use fs.readFile() and JSON.parse().

    Things to keep in mind:

    1. JSON.parse() and JSON.stringify() must always be wrapped in a try/catch block or otherwise your app will crash (or use tryjson module from npm).
    2. Never use methods of the fs modules with "Sync" in their name or otherwise your app will be blocked from serving requests.
    3. You need to implement locking and synchronization of the access to files or otherwise your data will get corrupted - this is the most difficult and most important part, and this is the reason why people use databases for that sort of things.
    0 讨论(0)
提交回复
热议问题