0

I asked this question for PHP a long time ago. The same applies for Node.js the code below seems a little slow when using in a loop - is there a way for writing this in pure Node.js vanilla JavaScript without plugins or React.js etc?

const dirname = 'cdn-assets/'

fs.readdir(dirname, function(err, files) {
    if (err) {
       // some sort of error
    } else {
       if (!files.length) {
           // directory appears to be empty
       }
    }
});

Also, can I write a further conditional to check:

if(directory_has_these_files('.js, .css, .jpg, .svg, .mp4'))

1 Answer 1

1

So if you do this

fs.readdir('/path/to/empty_dir', (data, err) => console.log(data, '.....', err)) 

You'll see that the result is:

null '.....' []

So your code can be simplified as

fs.readdir(dirname, (err, files)  => {
if (err && !files) {
    console.error(err)
}

console.info('the files --> ', files)

let regexp = RegExp('.jpeg|.doc|.png|.zip', 'gi')

for(result in files) {
    if(regexp.test(files[result])) {
        console.log('I have the following', files[result])
    }
}});

However....

We want this quick, modern and efficient, don't we?!

So this is even better:

fs.readdir(dirname, (err, files)  => {
    if (err && !files) {
        console.error(err)
    }

    let regexp = RegExp('.jpeg|.doc|.png|.zip', 'gi');

    files.filter(
        file => file.match(regexp)
    ).map(
        result => console.log('I have the following',result)
    );

});

One of the advantages to using a map on a directory, is that you'll guarantee the preservation of order, it also looks cleaner.

Map is built-in iterable — Object is not, this is not to say the Map is a replacement for Object, there are use cases for both. That's another story.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.