1

I'm trying to push the content of my folder inside an array named icon. However, the array is filled only inside the scope of the readdir but after that, it's empty and I don't know why.

const Discord = require('discord.js');
const client = new Discord.Client();
const path = require('path');
const fs = require('fs');

var icon = [];

function fillArray(arr) {
    const dirPath = path.join(__dirname, 'media');
    fs.readdir(dirPath, function (err, files) {
        if (err) {
            return console.log('Unable to scan directory: ' + err);
        }
        files.forEach(function (file) {
            arr.push(file);
        });
        console.log('value ==> ' + arr); // array is fill here
    });
    console.log('empty here ==> ' + arr); // array is empty 
    return arr;
}

fillArray(icon);
Kind Contributor
  • 17,547
  • 6
  • 53
  • 70
  • #moderators linking similar answers doesn't help the poster find the precise issue for this scenario. I would prefer that specific instances like this of async problems had direct code answers. Async code can be hard to understand and solve, even if you learn of the nature of the problem. Each instance of an async issue can have different strategies for solution. – Kind Contributor Jul 06 '20 at 12:32

1 Answers1

2

because, fs.readdir is async, use callback function like below:

function fillArray(arr, callback) {
  const dirPath = path.join(__dirname, "media");
  fs.readdir(dirPath, function (err, files) {
    if (err) {
      return console.log("Unable to scan directory: " + err);
    }
    files.forEach(function (file) {
       arr.push(file);
    });
    console.log("value ==> " + arr); // array is fill here
    callback(arr);
    });
  }

 fillArray(icon, (content) => {
   console.log("content: ", content);
 });
iamsohel
  • 387
  • 3
  • 7