const testFolder = '../assets';
const fs = require('fs');
const array=[]
const pattern=/gif/
fs.readdir(testFolder, (err, files) => {
files.map(file => {
if(file.search(pattern)>0)
array.push(file)
});
// console.log(files)
});
console.log(array)
It should be printing an array of all the files containing .gif extension .But it is printing an empty array .Not sure why the heck this is happening …
2
Answers
The console.log(array) call will happen before the array is actually populated, since the callback will take a little time to be called.
If you place the log statement within the callback, you’ll get the list of files as expected.
I’d also suggest using
Array.filter
overArray.map
in this case.You could also use
fs.readdirSync
if you wish to use a synchronous version of readdir.It’s because fs.readdir is async, you’ve to put the console log in the callback or use an await statement !