Search code examples
javascriptnode.jsmodule.exports

why module.exports return code as a text?


The problem I'm having is that when using module.exports I'm getting the output as text.

profile.js

const dbProfile = require("./dbProfile");

async function User(interaction) {
  const embed = new EmbedBuilder()
    .setColor(0x0099ff)
    .setTitle("user profile ")
    .setURL("https://https://www.youtube.com/watch?v=dQw4w9WgXcQ")
    .setDescription(`ExarID: ${dbProfile.profileInfo}`);
  await interaction.reply({
    ephemeral: true,
    embeds: [embed],
    fetchReply: true,
  });
  return 0;
}

dbProfile.js

const db = require("./dbStart");

module.exports = {
  profileInfo: function () {
    console.log(db.users);
    return db.users;
  },
};

dbStart.js

exports.users = function () {
  conn.query("SELECT ExarID FROM users", function (err, result, fields) {
    if (err) {
      console.log(err);
    }
    console.log(JSON.parse(result));
    return result;
  });
};

What the bot replies:

screenshot


Solution

  • You're never running your functions, and the .toString() of uncalled functions returns the source code.

    You need to change your code to call the functions

    in dbProfile.js

    const users = db.users();
    console.log(users)
    return users;
    

    in profile.js

    .setDescription(`ExarID: ${dbProfile.profileInfo()}`)
    

    You also have a bug in dbStart.js since you're never actually returning anything (see How do I return the response from an asynchronous call?)

    This involves changing all your code to work asynchronously

    profile.js

    const dbProfile = require("./dbProfile");
    async function User(interaction) {
      const profileInfo = await dbProfile.profileInfo();
      const embed = new EmbedBuilder()
        .setColor(0x0099ff)
        .setTitle("user profile ")
        .setURL("https://https://www.youtube.com/watch?v=dQw4w9WgXcQ")
        .setDescription(`ExarID: ${profileInfo}`);
      await interaction.reply({
        ephemeral: true,
        embeds: [embed],
        fetchReply: true,
      });
      return 0;
    }
    

    dbProfile.js

    const db = require("./dbStart");
    module.exports = {
      profileInfo: async function () {
        const users = await db.users();
        console.log(users);
        return users;
      },
    };
    

    dbStart.js

    exports.users = function () {
      return new Promise((resolve) => {
        conn.query("SELECT ExarID FROM users", function (err, result, fields) {
          if (err) {
            console.log(err);
          }
          console.log(JSON.parse(result));
          resolve(result);
        });
      });
    };