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)
Balizok
  • 904
  • 2
  • 5
  • 19
  • Please refer [is there a require for json in node.js](https://stackoverflow.com/questions/7163061/is-there-a-require-for-json-in-node-js) – sainath chorghe Jul 06 '21 at 14:49

3 Answers3

1

You can simply import json file on the beginning:

const dactylo = require('<path_to_json>.json');
hp10
  • 602
  • 6
  • 11
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.

mikach
  • 2,427
  • 2
  • 14
  • 15
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.