简体   繁体   English

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

[英]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.

相关问题 在node.js中的fs.read中指定读取文件中的数据字段 - Specify data fields in read file from fs.read in node.js 节点文件系统 (fs.writeFile) 在 Meteor.js 中默认写入何处? - Where does node file system (fs.writeFile) writes to on default in Meteor.js? 在node.js套接字中写入和'数据'事件 - Writes and 'data' events in node.js sockets 用Node.js的FileSystem(fs)模块将多个DOM元素保存和加载为JSON的最干净方法是什么? - What is the cleanest way to save and load multiple DOM elements as JSON with the FileSystem(fs) Module from Node.js? 如何在node.js中指定模块路径 - How to specify module path in node.js 从 node.js(fs 模块)中的文件 stream 中删除最后一个字符 - Removing the last character from file stream in node.js (fs module) 使用 fs 模块在 node.js 中更改 html 页面文件 - Changing html page file within node.js using fs module 使用fs和http模块使用Node.js下载zip文件不起作用 - Downloading a zip file with Node.js using fs and http module not working 如何将读取数据从 await readFile 传递到 node.js 的 fs 模块中的 writeFile? - How to pass read data from await readFile to writeFile in fs module of node.js? 为什么在 node.js fs 模块中删除文件被命名为“取消链接”? - why in node.js fs module removing files is named “unlink”?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM