Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Listing files in a directory, where the filename matches a regex in JS

I want to get all filenames within a directory that follow a specific pattern. I found out, that I can accomplish this by doing the following:

var fs = require('fs');

fs.readdir( dir, function(err, list) {
    if(err)
        throw err;
    var regex = new RegExp(".*");
    list.forEach( function(item) {
    if( regex.test(item) ) 
       console.log(item);
    }); 
});

I was wondering, if there is another possibility to do this without using a loop, e.g. passing a regex to fs.readdir(..).
Is that somehow possible, or do I have to use a loop?

like image 954
Tobi Avatar asked Oct 20 '22 14:10

Tobi


1 Answers

You can use the npm atmosphere package to use other NPM modules. This will let you use the popular glob NPM module. This uses glob patterns, which are more common for matching file names than regex patterns.

like image 93
sbking Avatar answered Oct 23 '22 04:10

sbking