繁体   English   中英

有没有办法指定(在另一个文件中)node.js 模块 FS 写入数据的位置

[英]Is there a way to specify where (in another file) The node.js module FS writes the data

我有一个问题,当我使用 fs 方法时fs.appendFileSync(example.json, jsonString, {'flags': 'a+'}); 它会将数据写入 JSON 文件...但不在数组中,我需要将数据放入...当我运行代码时,JSON 文件的内容将如下所示{people:[ {where I want the data to go} ] }{data is written here}我不知道如何指定我需要将数据放在数组中的人......我也有多个对象在数组中的问题......他们需要逗号我也怎么做?

您不能通过附加来修改文件的内容。 您必须将所有数据读入 object,修改它然后覆盖内容。 请参阅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))

方法 -1 在某个变量中读取该文件。 然后将您的数据添加到 json 变量中。 然后重写文件。

方法 - 2 使用 fs.write 提供需要添加数据的 position。

fs.writeSync(fd, string, position)

position 将根据您的 json 固定并计算。

暂无
暂无

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

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