TransWikia.com

nodejs writing to JSON into a specific path

Stack Overflow Asked by C4LLM3P3T3R on February 18, 2021

So I’m creating a discord bot that will handle two languages. Polish and English (because I’m from Poland), and I made a JSON file that stores the lines that the bot will be sending. Because this will be a global bot, I need to know which server has which language set. Then the bot upon turning on will be checking if id of this server that he is on is in that JSON path (servers), if not then he will write this server-id and assign a default language to it (English). But how do I do it? How can I write in javascript to a specific path in my json? I know how to read from a specific path but I don’t know how to read.

The json:

{
"servers":[
                 //here i have an array of servers but i don't know how to write stuff to it
]

"pl"{
    "braumError": "Hmm, no nie wiem... Coś jest nie tak I przez to nie mogę odczytać twoich punktów maestri. Spróbuj ponownie. Jeśli jesteś pewny, że wpisałeś wszystko dobrze to może być wina mojego programisty. Przy okazji przekaż mu, że może być problem z api-key'em",
    "braumStatusError": "Musisz podać jaki status chcesz mieć!",
    "braumYasuoMaestryError": "Tak, słyszałem on tym iońskim samuraju wiatru, podobno zabił swojego mistrza. Tak czy siak mogę ci powiedzieć ile masz na nim maestrii. Musisz tylko podać mi swój nick i region na którym grasz. Będzie to wyglądać mniej więcej tak !yasuo <nick> <region>",
    "braumChampionError": "Hmm... Przeszukałem wszyskie freljordzkie biblioteki i nic nie znalazłem, może to nie istnieje. Sprawdź czy dobrze wszystko wpisałeś i spróbuj ponownie!",
    "braumStatusPlaying": "gra",
    "braumStatusListening": "slucha",
    "braumStatusWatching": "oglada",
    "braumStatusStreaming": "streamuje",
    "braumYasuoMaestry": "{player} masz {punkty} punktów maestrii na yasuo!"
}

"en"{
    "braumError": "Hmm, I don't know.... Something's wrong and i can't read your mastery points. Try again. If you're sure that you've spelled everytning right it may be my creator's fault. You can let him know that it's probably an api key problem.",
    "braumStatusError": "You need to specify what type of status you want!",
    "braumYasuoMaestryError": "Yeah, I've heard about this ionian wind samurai, someone told me that he killed his master. Anyways braum can tell your mastery on him if you tell me your nickname, and a region. It will look something like this !yasuo <nick> <region>",
    "braumChampionError": "Hmm... I searched all the libraries in freliord, I couldn't find anything, maybe this doesn't exist. Check your spelling and try again! ",
    "braumStatusPlaying": "playing",
    "braumStatusListening": "listening",
    "braumStatusWatching": "watching",
    "braumStatusStreaming": "streaming",
    "braumYasuoMaestry": "{player} you have {punkty} maestry point on yasuo!"
}


}

6 Answers

Answer to Thank you! That's what I'm looking for. I did a foreach loop to loop through every serverid in my serverId array and pushed it into son. And one more thing. How can i know if the server I'm on (the bot is on) is in the array? Like { "servers":[{"12342134": "en"}]} and i want to check if 12342134 is on in that array. I have the server id but i want to know if it's on the array (in the key not the value)

var serverId = "server01";

const allServer = []

// extract all the server id from the object
config.servers.forEach(d => allServer.push(...Object.keys(d)))

console.log(allServer.includes(serverId)) // true

Correct answer by Abhishek on February 18, 2021

Try this

// var serverId = client.guilds.cache.map(guild => guild.id); // getting server id 
var serverId = "server01"; // getting server id 
var lang = "en"; // lang
// var config = readConfigFile(); //reading file from config yes there is JSON.parse
const config = {servers: []} // assuming JS is JSON.parse of JSON
var server = {[serverId] : lang};

config.servers.push(server)
console.log(config)

Answered by Abhishek on February 18, 2021

Okay, I've got how to write to a path but, when I'm writing to this:

"servers":{

},

It writes something like this "servers":"[object Object][object Object]",

brackets go poof and instead of server id it writes object Object. Why?

var serverId = client.guilds.cache.map(guild => guild.id); // getting server id 
var lang = "en"; // lang
var config = readConfigFile(); //reading file from config yes there is JSON.parse
var server = {serverId : lang};
console.log(server);
config.servers = config.servers + server;
config = JSON.stringify(config);
saveConfigFile(config);

and the console.log(server); for some reason spits out {serverId: "en"}. Why serverId is not a variable?

Answered by C4LLM3P3T3R on February 18, 2021

It sounds like you're wanting to be able to load the content of your JSON file into your bot, make edits to it, and then write them back to file again. If so, something like the following would work for managing the file (without any error handling):

const fs = require('fs');

const pathToJsonFile = 'some/path/your-file.json';

function readConfigFile(){
  const asJavascript = JSON.parse(fs.readFileSync(pathToJsonFile,'utf8'));
  return asJavascript;
}

function saveConfigFile(configAsJavascript){
  fs.writeFileSync(pathToJsonFile,configAsJavascript);
}

function addServerToConfig(server){
  const config = readConfigFile();
  config.servers.push(server);
  saveConfigFile(config);
}

You could then call addServerToConfig() from your bot.

If you want to keep track of both servers and their language, I'd recommend either storing them as an array of objects, e.g.

"servers":[{"name":"server-name-or-id-or-whatever", "language": "pl"}]

Or just storing a single object instead of an array, since that way you can do lookups without having to search, e.g.

"servers": {"server-id-1": "pl", "server-id-2": "en"}

Answered by bscotchAdam on February 18, 2021

insatll the package npm install fs

Then you must call upon the FS manager

fs = require('fs);

"servers":[
            fs.readFileSync('filepathhere' , 'utf8') function(err, data){
             if (err) {throw err}
             var data = data;
              return data;
              };
             //for writing to those files 
            try {
        if(fs.existsSync(arrayname+".txt")) {
            console.log("The file exists.");
        } else {
            fs.appendFile(arrayname+".txt", arrayname.tostring(), function (err){
                if (err) throw err;
                    console.log('Saved!');
            });
            console.log('The file does not exist.');
     }
} catch (err) {
        console.error(err);
}

]

Hope this helps if there's any specific questions regarding the specific array please let me know

Answered by swift gaming on February 18, 2021

If you want add a new item to an Array use .push() function

Answered by iKaio on February 18, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP