Dimo Chanev
Dimo Chanev

Reputation: 129

Get all files with specified extension node.js

I am using node.js. I want to loop through all files with extension .coffee, but I have nowhere found an example.

Upvotes: 0

Views: 183

Answers (1)

Zain Zafar
Zain Zafar

Reputation: 1607

Following function will return all the files in the specified directory with the regex provided.

Function

var path = require('path'), fs=require('fs');

function fromDir(startPath,filter,callback){

    //console.log('Starting from dir '+startPath+'/');

    if (!fs.existsSync(startPath)){
        console.log("no dir ",startPath);
        return;
    }

    var files=fs.readdirSync(startPath);
    for(var i=0;i<files.length;i++){
        var filename=path.join(startPath,files[i]);
        var stat = fs.lstatSync(filename);
        if (stat.isDirectory()){
            fromDir(filename,filter,callback); //recurse
        }
        else if (filter.test(filename)) callback(filename);
    };
};

Usage

fromDir('../LiteScript',/\.coffee$/,function(filename){
    console.log('-- found: ',filename);
});

Upvotes: 1

Related Questions