简体   繁体   中英

Node.js, Express.js - Write to JSON file

I'm writing an Express.js application, which should be able to create a JSON formatted output with request information and accordingly write this information to JSON file. I'm new to Node&Express and so far I've tried to use fs.writeFile('file.json', data, function(err){}) but I need data to be appended to file.json . The perfect output should be:

[
  {somekey: someValue},
 //each time the new request is sent the object should be added here
  {shomeKeyFromNewRequest: someValueFromNewRequest}
]

Your example doesn't show it being appended to the file. Appending would just add the text to the end .

You need to:

  1. Read the file
  2. Parse the content to a JS array
  3. Add the new data to the array
  4. Stringify the whole thing to JSON
  5. Overwrite the file with the new content

You may want to look at using file locking to avoid overlapping writes losing you data.

You'd probably be better off using a real database instead.

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