0

I'm developing a discord bot and i wanted to send a random sentence from my dactylo.json file when the user sends a specific message. However, when trying to access data from this file, I get an "undefined" error like it couldn't read my json file. I looked over many previous questions but couldn't find an answer that helped me, even though it helped other people. I'm sure I'm missing something but I can't seem to find what...

Here's my code from dactylo.json :

{
    "sentences":[
        {
            "sentence": "Un dragon gradé dégrade un gradé dragon.",
            "top":"0",
            "player":"Personne"
        },
        {
            "sentence":"Le mur murant Paris rend Paris murmurant.",
            "top":"0",
            "player":"Personne"
        },
        {
            "sentence":"Le cricri de la crique crie son cri cru et critique car il craint que l'escroc ne le croque et ne le craque.",
            "top":"0",
            "player":"Personne"
        }
    ]
}

And my code from dactylo.js where I try to get data :

const fs = require('fs');

module.exports = {
    name: 'dactylo',
    description: 'Démarre une partie de dactylo',
    execute(message) {
        message.reply("Recopiez la phrase suivante le plus rapidement possible :")
        const data = fs.readFileSync('C:/Users/steph/Documents/Discord Bot/commands/fun/dactylo.json');

        const sentences = data.sentences;
        var sentence = sentences[Math.floor(Math.random() * sentences.length)];
        message.channel.send(sentence);
    },
};

And the error I get in case it helps :

TypeError: Cannot read property 'length' of undefined
    at Object.execute (C:\Users\steph\Documents\Discord Bot\commands\fun\dactylo.js:11:71)
    at Client.<anonymous> (C:\Users\steph\Documents\Discord Bot\main.js:42:11)
    at Client.emit (events.js:375:28)
    at MessageCreateAction.handle (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\actions\MessageCreate.js:31:14)
    at Object.module.exports [as MESSAGE_CREATE] (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\handlers\MESSAGE_CREATE.js:4:32)
    at WebSocketManager.handlePacket (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketManager.js:384:31)
    at WebSocketShard.onPacket (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:444:22)
    at WebSocketShard.onMessage (C:\Users\steph\Documents\Discord Bot\node_modules\discord.js\src\client\websocket\WebSocketShard.js:301:10)
    at WebSocket.onMessage (C:\Users\steph\Documents\Discord Bot\node_modules\ws\lib\event-target.js:132:16)
    at WebSocket.emit (events.js:375:28)
1

3 Answers 3

1

You can simply import json file on the beginning:

const dactylo = require('<path_to_json>.json');
Sign up to request clarification or add additional context in comments.

Comments

0

You can use require to automatically parse JSON for you

const data = require('path/to/file.json');

Also, it's better practice to use a relative path to the file instead of an absolute.

Comments

0

In your case, the fs.readFileSync function returns a Buffer, not the parsed json content as you expect.

In order to obtain the parsed JSON content, you need to follow two steps:

  1. Read the .json file content as text
  2. Parse the text with JSON.parse

The following code illustrates how it works:

const jsonPath = 'C:/Users/steph/Documents/Discord Bot/commands/fun/dactylo.json';
const jsonText = fs.readFileSync(jsonPath, "utf8"); 
const jsonObject = JSON.parse(jsonText);
console.log(jsonObject.sentences.length);   // 3

Notice that the second parameter passed to the fs.readFileSync function tells the function to return the file content as String and not as Buffer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.