Call a .json from module.exports

Viewed 52

To avoid having to change every emoji from every file whenever I switch an emoji, I decided to place an emojis.json and call the emoji from there.

emojis.json

{
    "loading": "<a:loading:847653387343626301>",
    "pressf": "<:pressf:862166705911758909>"
}

Exampleping.js

const emoji = require('../emojis.json')

module.exports = {
    name: 'ping',
    execute(message, args) {
        message.channel.send(`${emoji.loading}Pong.`)
    }
}

Is this the right way? I'm open to new/better ideas. Btw it errors: code: 'MODULE_NOT_FOUND',

2 Answers

Well, your approach is correct to a certain extent. Only issue is that you have imported a json file instead of js file and hence it throws an error.

Correct way of achieving this, is having a emojis.js file with your json object exported using module.exports

// emojis.js
module.exports = {
    loading: "<a:loading:847653387343626301>",
    pressf: "<:pressf:862166705911758909>"
};


// Exampleping.js
const emojis = require('../../emojis.js')
module.exports = {
    name: 'ping',
    execute(message, args) {
        message.channel.send(`${emoji.loading}Pong.`)
    }
}

Your code is clean except your import statement is not referring to the emojis.json file. To make it more clear, the script failed to locate the file, which means emojis.json is not located inside the same directory as exampleping.js (require('./emojis.js')).

Based on my experience with Discord bot development, I believe you placed emojis.json in your root directory while exampleping.js is placed inside a directory commonly named "commands". With that being said, all you need is to exist the command directory by adding another . to require().

      const emojis = require('../emojis.js');
      //instead of ./emojis.json

See HTML File Path

Related