0

i have written a method to read all the file names and pass it to array. It reads correctly and pushes to array and if i print its showing all values.

However if i try to print the array outside the method, its showing as null. Can anyone help me how it can print outside :

const testFolder = '../features/';
const fs1 = require('fs');

let a = [];

fs1.readdir(testFolder, (err, files) => {
  files.forEach(file => {
    a.push(file);

    });
})

console.log(a);

Now a prints as empty. How to get a with all the values

wanderors
  • 2,030
  • 5
  • 21
  • 35

1 Answers1

0

It's because fs.readdir is asynchronous, the array is not yet populated when you print it in the console. If you wait until the read is complete it will work as expected!

If you move the log statement inside the readdir callback it would also be fine.

You can try readdirsync to get a synchronous call, e.g.

let files = fs.readdirSync(testFolder);
console.log (files);
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40