0

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

5
  • What OS are you using? A *nix flavour, Mac or Windows? Commented Apr 18, 2016 at 8:09
  • @NZD I'm using Arch Linux, but I will be happy if it works on Windows and Mac, too. Commented Apr 18, 2016 at 8:10
  • You are probably looking for fs.readdir() and perhaps path.extname(). Commented Apr 18, 2016 at 8:11
  • @jfriend00 and the use regex to validate if it is *.coffee? Isn't this a bit slow, because it reads all unneeded files, too? Commented Apr 18, 2016 at 8:15
  • 1
    @DimoChanev - Something is going to read all the file entries from disk anyway so the speed difference whether you do it in node.js or it's done in the OS is not likely a big difference. You can use path.extname() to parse off the extension to see if it's .coffee. Commented Apr 18, 2016 at 8:18

1 Answer 1

1

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);
});
Sign up to request clarification or add additional context in comments.

1 Comment

see the jfriend00's comment for easyer way of doing this, But is is working well, too :)

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.