最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Listing files in a directory, where the filename matches a regex in JS - Stack Overflow

programmeradmin1浏览0评论

I want to get all filenames within a directory that follow a specific pattern. I found out, that I can acplish 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?

I want to get all filenames within a directory that follow a specific pattern. I found out, that I can acplish 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?

Share Improve this question asked Feb 21, 2014 at 12:27 TobiTobi 2,0402 gold badges29 silver badges50 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 2

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 mon for matching file names than regex patterns.

According to the documentation, the function fs.readdir does not take a regular expression to filter file names before calling the callback. It mentions explicitly using readdir(3) which has no notion of regular expression.

So you have to loop through the results and filter them. Or perhaps use a 3rd party library that would do it for you but fs.readdir won't by itself do it.

发布评论

评论列表(0)

  1. 暂无评论