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.
EDIT: The code posted is from addinsult.js
Where are you defining local storage? If it's a module you need to 'require' it.
this line roasts = localStorage.getItem("roasts").split(/\r?\n/);
Is trying to do stuff with something called "localStorage", which has never been defined.
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'));