簡體   English   中英

我如何將數據存儲在 json 文件中連續 discord.js

[英]how can i store data in json file Continuous for discord js

我想從用戶那里獲取消息信息並將其保存在一個 JSON 文件中並且不斷添加此數據,但是使用以下代碼不斷替換此數據。 而且我不替換數據我想添加數據這是我的代碼:

const fs = require("fs");
const { Client, Intents } = require("discord.js");

const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],
});
const now = new Date();
const obj = {
  table: [],
};
let confirm = false;
const { badWords } = require("../badWordList.json");
client.on("message", async (message) => {
  if (message.author.bot) return;
  for (let i = 0; i < badWords.length; i++) {
    if (message.content.toLowerCase().includes(badWords[i].toLowerCase()))
      confirm = true;
  }
  if (confirm) {
    obj.table.push({
      name: message.author.username,
      date: `${now.getFullYear()}/${now.getMonth()}/${now.getDate()}`,
      message: message.channel.messages.channel.lastMessage.cleanContent,
    });
    fs.writeFile("myjsonfile.json", JSON.stringify(obj), function (err) {
      if (err) throw err;
      console.log("complete");
    });
  }
});

使用fs.writeFile()時,它會替換文件的內容,如文檔中所寫。

乍一看,您可能想使用fs.write() ,請參閱文檔了解用法。

但是 NodeJS 文檔說:

在同一個文件上多次使用 fs.write() 而不等待回調是不安全的。 對於這種情況,建議使用fs.createWriteStream()

由於您處於異步模式,您應該定義一個 write stream 到文件然后寫入它,它給你這樣的東西:

// -snip-
const whateverJsonFileStream = fs.createWriteStream("myjsonfile.json");

client.on("message", async (message) => {
    //-snip-

    if (confirm) {
        obj.table.push({
            name: message.author.username,
            date: `${now.getFullYear()}/${now.getMonth()}/${now.getDate()}`,
            message: message.channel.messages.channel.lastMessage.cleanContent,
        });

        whateverJsonFileStream.write(JSON.stringify(obj), function (err) {
            if (err) throw err;
            console.log("complete");
        });
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM