[英]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: 如果您想使用稍微复杂一些的文件管理解决方案(但实施起来非常简单),则可以:
This way, you don't need to worry about files not being completely written etc. 这样,您不必担心文件没有被完全写入等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.