简体   繁体   English

Node.js更新文件中的JSON数据

[英]Node.js update JSON data in file

I have to write some JSON data on a file. 我必须在文件上写一些JSON数据。 Some JSON objects must be update during the execution of the program and these updates must be saved in the file (for example objects in array). 某些JSON对象必须在程序执行期间进行更新,并且这些更新必须保存在文件中(例如,数组中的对象)。

Exist a way to do this without rewrite the entire file? 是否存在一种无需重写整个文件的方法?

JSON structure: JSON结构:

{
    "varA": {
        "varA1": value,
        "varA2": value,
    },
    "varB": value,
    "varC": value,
    "varD": value,
    "array": [
        { obj1 },
        { obj2 },
        { obj3 },
    ]
}

If you have more than one file, I would strongly encourage you to use MongoDB, as it is exactly what it is good for. 如果您有多个文件,我强烈建议您使用MongoDB,因为这正是它的优点。

With MongoDB you can do things like (from docs ): 使用MongoDB,您可以执行以下操作(来自docs ):

   db.books.update( { item: "Divine Comedy" },
             {
               $set: { price: 18 }, // set property value
               $inc: { stock: 5 },   // increment etc field value

             } )

   // add value in array
   db.bios.update(
     { _id: 1 },
     {
        $push: { awards: { award: "IBM Fellow", year: 1963, by: "IBM" } }
     }

)

UPDATE: Also, since you mentioned that files are in fact configuration, check out what Grunt can do. 更新:另外,由于您提到文件实际上是配置文件,因此请查看Grunt可以做什么。 For instance answer to this question Updating file references in a json file via a grunt task 例如对此问题的答案通过grunt任务更新json文件中的文件引用

If you want slightly more sophisticated solution to file management (yet quite simple to implement), I'd: 如果您想使用稍微复杂一些的文件管理解决方案(但实施起来非常简单),则可以:

  1. create a new file instead of trying to rewrite an existing file (with a new filename every time). 创建一个新文件,而不是尝试重写一个现有文件(每次都使用一个新文件名)。 I'd suggest using something that includes a time stamp (either human readable or as milliseconds). 我建议使用包含时间戳记的东西(人类可读或以毫秒为单位)。
  2. and always look for the newest file when loading/sync'ing the file 并在加载/同步文件时始终寻找最新文件
  3. Purge the old files when you "find" a newer one and it reads successfully. 当您“找到”较新的文件成功读取时,请清除旧文件。 If the file doesn't read successfully, something has happened. 如果文件未成功读取,则说明发生了某些情况。 Fall back to the next file, and ideally delete the bad file. 退回到下一个文件,并理想地删除错误的文件。 Or, just wait until a new file is successfully written. 或者,只需等待成功写入新文件。

This way, you don't need to worry about files not being completely written etc. 这样,您不必担心文件没有被完全写入等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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