未定义本地存储
我正在尝试在javascript中使用localstorage来保存两次执行之间的数据.这是使用它的代码
I'm trying to use localstorage in javascript to save data between executions. Here is the code using it
const commando = require('discord.js-commando');
roasts = localStorage.getItem("roasts").split(/\r?\n/);
class RoastMe extends commando.Command {
constructor(client){
super(client, {
name:'addroast',
group:'insult',
memberName:'addroast',
description:'Add a roast to the !roastme archive'
});
}
async run(message, args){
if(args.length==0) message.reply("That aint a roast.");
else{
roasts.push();
roasts[roasts.length-1] = args;
var save = "";
for(var i = 0; i < roasts.length; i++){
save += roasts[i] + "\n";
}
localStorage.setItem("roasts", save);
}
}
}
module.exports = RoastMe;
这是我尝试运行它时产生的错误
This is the error it produced when i tried to run it
ReferenceError: localStorage is not defined
at Object.<anonymous>
//location of error
(/home/ubuntu/workspace/commands/insult/addinsult.js:2:1)
at Module._compile (module.js:569:30)
at Object.Module._extensions..js (module.js:580:10)
at Module.load (module.js:503:32)
at tryModuleLoad (module.js:466:12)
at Function.Module._load (module.js:458:3)
at Module.require (module.js:513:17)
at require (internal/module.js:11:18)
at /home/ubuntu/workspace/node_modules/require-all/index.js:52:46
at Array.forEach (native)
如果在执行之间有更好的存储数据的方法,请告诉我.否则,您能否解释为什么这行不通?谢谢.
If there's a better way to store data between executions, please let me know. Otherwise, could you explain why this isn't working? Thanks.
发布的代码来自addinsult.js
The code posted is from addinsult.js
您在哪里定义本地存储?如果是模块,则需要要求"它.
Where are you defining local storage? If it's a module you need to 'require' it.
此行 roasts = localStorage.getItem("roasts").split(/\ r?\ n/);
正在尝试使用从未定义的名为"localStorage"的东西.
Is trying to do stuff with something called "localStorage", which has never been defined.
如果我没有记错的话,您似乎正在尝试使用此模块: https://www.npmjs.com/package/node-localstorage 我在该页面上找到了有关如何使用它的说明.
It looks like you're trying to use this module if i'm not mistaken: https://www.npmjs.com/package/node-localstorage I found these instructions on how to use it on that page.
if (typeof localStorage === "undefined" || localStorage === null) {
var LocalStorage = require('node-localstorage').LocalStorage;
localStorage = new LocalStorage('./scratch');
}
localStorage.setItem('myFirstKey', 'myFirstValue');
console.log(localStorage.getItem('myFirstKey'));