-1

So I have this code:

const Discord = require("discord.js");
const bot = new Discord.Client();
const rf = require("select-random-file");
const token = "{DATA REVOKED}";
const prefix = "bot:"
const dir = './RandomImage'
function ranIm(){
    rf(dir, (err, file) => {
        console.log(`The random file is: ${file}.`)
        return file;
    }) 
   
}

bot.on('ready', () =>{
    bot.user.setStatus("Online");
    bot.user.setActivity('with '+bot.guilds.cache.size+" servers!");
    console.log("{BOT INITIALISED} PREFIX IS "+prefix)
})
bot.on("message", msg=>{
    let contentDown =msg.content.toLowerCase();
    let args = contentDown.substring(prefix.length).split(" ");
    if(contentDown.substring(0,prefix.length)===prefix){
        switch(args[0]){
            case 'random':
                console.log(ranIm());
                msg.channel.send("Here is your image: <3", { files:["./RandomImage/"+ranIm()]}).then(() => {
                    msg.react("✅")}, err => {console.log("Error [random]"); msg.react("❌") });          
                break;
        }
    }
})
bot.login(token);
But when I run the "random" command, it just logs "undefined" and the function "ranIm" has a console.log that returns a proper response like "untitled.png". How can I return the same thing as the console.log in the function?
Jason
  • 19
  • 4

1 Answers1

0

Your function ranIm itself does not return anything. The return file is inside the second argument of the rf function. So the return file is now the result of the rf(dir, ...) function.

So you need a callback parameter for the ranIm function like this:

function ranIm(callback){
    rf(dir, (err, file) => {
        console.log(`The random file is: ${file}.`)
        callback(file)
    }) 
   
}

ranIm(function(randomFile) {
   // Do stuff with random file
})

Another option is using Promises

function ranIm(callback){
    return new Promise((reject, resolve) {
        rf(dir, (err, file) => {
           if (err) reject(err);
           resolve(file);
        })
    })
}
ranIm().then(file => {
   // Do stuff with random file
})
n9iels
  • 867
  • 7
  • 21