【问题标题】:Persistence of a variable through program restarts通过程序重新启动变量的持久性
【发布时间】:2018-02-13 04:37:16
【问题描述】:

我对 JavaScript 有点陌生,我想知道,在我关闭程序并重新打开后,如何让程序中的变量保持不变。

例如,如果我有:

//Call package
var Discord = require("discord.js");
var caterpieBot = new Discord.Client();
var nextClubMeeting;

//Listener Event for recieved messages
caterpieBot.on("message", message =>
{
  var sender = message.author; // who sent the message
  var msg = message.content.toUpperCase();
  var prefix = "!" //command to interact with caterpieBot
  var tempMsg = msg;
  var splitMsg = tempMsg.split(":")


  if(splitMsg[0] === "CATERPIE, PLEASE SCHEDULE OUR NEXT CLUB MEETING FOR")
  {
      message.channel.send("Yes " + sender + ", I will schedule the next club meeting for: " + splitMsg[1])

      nextClubMeeting = splitMsg[1]; //I WANT "nextClubMeeting" TO //PERSIST ON RESTART!

  }

我让用户在程序运行时将该号码更改为2。当我重新启动程序时,如果我尝试打印userInputedNumber,它将返回为undefined。我如何让我的程序在重新启动后记住userInputedNumber = 2? (2 将是用户输入的任何数字)。

【问题讨论】:

  • 浏览器还是节点?
  • 我正在使用 Node.js。我还编辑了原始帖子,使其看起来更像我的程序。我正在为我的俱乐部编写一个不和谐的机器人。我剪掉了重要的部分
  • 最简单的方法可能是写入文件系统。例如。类似于 node-persist (github.com/simonlast/node-persist)。或者你可以使用redis之类的数据库将数据保存在内存中。
  • 我知道在 java 中你可以这样做: BufferedWriter writer = new BufferedWriter(new FileWriter(new File("ClubMeetingInfo.txt"))); writer.write(nextClubMeeting); writer.close(); : 但这在 JS 中可能吗?这样我就可以将字符串存储在 .txt 文件中,并在每次程序启动时将变量重置为 .txt 中的字符串

标签: javascript node.js persistence discord.js


【解决方案1】:

嗯,您可能需要设置一个数据库来存储该数据。在交换消息的前端还有其他“持久化”数据的方法。会话是一种较松散的方式,但这似乎更像是与该特定用户相关的用户特定输入。也许您可以在 MongoDB 中将其路由到您的应用程序中并存储它,并在以后需要时访问它?

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多