Created
November 23, 2012 09:44
-
-
Save victorsollozzo/4134793 to your computer and use it in GitHub Desktop.
recursively find all files in a directory with given extension in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var path = require('path') | |
var fs = require('fs') | |
function recFindByExt(base,ext,files,result) | |
{ | |
files = files || fs.readdirSync(base) | |
result = result || [] | |
files.forEach( | |
function (file) { | |
var newbase = path.join(base,file) | |
if ( fs.statSync(newbase).isDirectory() ) | |
{ | |
result = recFindByExt(newbase,ext,fs.readdirSync(newbase),result) | |
} | |
else | |
{ | |
if ( file.substr(-1*(ext.length+1)) == '.' + ext ) | |
{ | |
result.push(newbase) | |
} | |
} | |
} | |
) | |
return result | |
} | |
ext_file_list = recFindByExt('/mypath','ext') |
Just a recommendation, it would be safer and cleaner replacing the line 18:
if ( file.substr(-1*(ext.length+1)) == '.' + ext )
With the String method endsWith
:
if (file.endsWith(featureExtension)) {
Anyway, great job, you inspired and helped a lot of people. Thank you!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I would also add
!path.extname(file)
just to make sure the function doesn't look inside a macOS.app
, because it's actually a folder.I have it like this: