0
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 ...

1 Answers1

1

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 over Array.map in this case.

const testFolder = '../assets';
const fs = require('fs');

const pattern = /\.gif$/i
fs.readdir(testFolder, (err, files) => {
    const array = files.filter(file => pattern.test(file))
    console.log(array)
});

You could also use fs.readdirSync if you wish to use a synchronous version of readdir.

const testFolder = '../assets';
const fs = require('fs');

const pattern = /\.gif$/i
const allFiles = fs.readdirSync(testFolder)
const gifFiles = allFiles.filter(file => pattern.test(file))
console.log(gifFiles)
Terry Lennox
  • 29,471
  • 5
  • 28
  • 40
  • 1
    I would suggest using `regexp.test` ... `pattern.test(file)` since you just need the truthiness of the match ... I'd also suggest the pattern needs to be `/\.gif$/i` ... but that's just me being pedantic :p – Jaromanda X Jun 28 '23 at 08:49
  • Good points @JaromandaX, I think programmers are allowed to be pedantic :-).. I think that's a better answer. – Terry Lennox Jun 28 '23 at 08:51
  • 1
    pedantry is a pre-requisite for being a programmer :p – Jaromanda X Jun 28 '23 at 08:53