![](/img/trans.png)
[英]Error in serving JSON response with Node.js, MongoDB, and express after 1st response
[英]Node.js Function not updating value after 1st invoke
我最近對 Discord.js 框架感興趣,並且正在為服務器設計一個機器人。 提前為代碼的混亂道歉。
我面臨的問題是,在我第一次運行命令后,調用了 function, ticketValue
的值不會更新為我的 JSON 文件中的更新值。
const fs = require("fs");
module.exports = {
commands: ["ticket"],
minArgs: 1,
expectedArgs: "<message>",
callback: (message, arguments, text) => {
// Console Log to notify the function has been invoked.
console.log("FUNCTION RUN")
let jsondata = require("../ticketNum.json")
let ticketValue = jsondata.reportNews.toString()
// Turning the number into a 4 digit number.
for(let i = ticketValue.length; i<4;i++) {
ticketValue = `0${ticketValue}`
}
console.log(`#1 ${ticketValue}`)
// Creating the Discord Chanel
message.guild.channels.create(`report-incident-${ticketValue}`, {
type: 'text',
permissionOverwrites: [
{
id: message.author.id,
deny: ['VIEW_CHANNEL'],
},
],
})
// Adding one to the ticket value and storing it in a JSON file.
ticketValue = Number(ticketValue)+1
console.log(`TICKET VALUE = ${ticketValue}`)
fs.writeFile("./ticketNum.json",JSON.stringify({"reportNews": Number(ticketValue)}), err => {
console.log(`Done writing, value = ${ticketValue}`)
})
console.log(require("../ticketNum.json").reportNews.toString())
},
}
我相信這是由於一種叫做require cache的東西。 您可以在每次寫入 JSON 文件時使緩存無效,或者最好使用fs.readFile
來獲取最新內容。
還值得注意的是,您需要../ticketNum.json
但您正在寫入./ticketNum.json
。 這也可能是一個原因。
您似乎正在使用 JSON 文件作為數據庫,雖然根據您的項目規模這是完全可以接受的,但我會推薦一些更精致的東西,比如lowdb ,它仍然使用本地 JSON 文件來存儲您的數據,但提供更好的 ZDB464238D083ACE 與 1 一起工作.
僅當應用程序運行時文件為 static 時才應使用require
。
require
執行非常有用,尤其是當您加載大量具有相同依賴項的模塊時。require
還做了一些特殊的事情來在本地、全局等地方查找模塊。因此,如果文件在本地丟失並且require
進行搜索,您可能會看到意外的事情發生。 這兩件事意味着它不能很好地替代用於文件訪問和操作的fs
工具節點。
鑒於此,您應該使用fs.readFileSync
或其他讀取函數之一。 您已經在使用fs
進行寫入,因此就更改您require
的一兩行或讀取而言,這並不是一個很大的提升。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.