簡體   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