[英]Is there a way to specify where (in another file) The node.js module FS writes the data
I have an issue where when I use the fs method fs.appendFileSync(example.json, jsonString, {'flags': 'a+'});
我有一个问题,当我使用 fs 方法时
fs.appendFileSync(example.json, jsonString, {'flags': 'a+'});
it will write the data to the JSON file... But not in the array I need the data to be in... When I run the code the JSON files contents will look like this {people:[ {where I want the data to go} ] }{data is written here}
I have no idea as to how to specify that i need the data to be inside the array people... I also have the issue of multiple objects being in the array... They need to have commas how would I also do that?它会将数据写入 JSON 文件...但不在数组中,我需要将数据放入...当我运行代码时,JSON 文件的内容将如下所示
{people:[ {where I want the data to go} ] }{data is written here}
我不知道如何指定我需要将数据放在数组中的人......我也有多个对象在数组中的问题......他们需要逗号我也怎么做?
You can't modify the content of the file by appending to it.您不能通过附加来修改文件的内容。 You have to read all the data into a object, modify it an then overwrite the contents.
您必须将所有数据读入 object,修改它然后覆盖内容。 See this for a general idea.
请参阅this了解一般想法。
const fs = require('fs');
const data = require('./file.json') // node will parse json automatically
data.people.push({}) // the new data you want in the array
fs.writeFileSync('file.json', JSON.stringify(data))
method -1 read that file in some variable.方法 -1 在某个变量中读取该文件。 then add your data in that variable which is json.
然后将您的数据添加到 json 变量中。 then rewrite file.
然后重写文件。
method - 2 use fs.write provide position where data need to be added.方法 - 2 使用 fs.write 提供需要添加数据的 position。
fs.writeSync(fd, string, position)
position will be fixed and calculate it based on your json. position 将根据您的 json 固定并计算。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.