Last active
April 25, 2018 20:28
-
-
Save num8er/5dea4389acb88aa17f7fa3e42b6aba5b to your computer and use it in GitHub Desktop.
Recursive search for files by filename in nested directories
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
Let's write a class that looks for file in nested directories. | |
We need 2 files: | |
1) Module file: `FileSearch.js` | |
2) Usage (example) code that use that `FileSearch` module. | |
p.s. module and usage (example) code are written in ES6 standart. |
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
const | |
fs = require('fs'), | |
path = require('path'), | |
EventEmitter = require('events'); | |
class FileSearch extends EventEmitter { | |
constructor(filename, startDir) { | |
super(); | |
this._filename = filename; | |
this._dir = startDir; | |
} | |
_find(dir) { | |
let self = this; | |
fs.readdir(dir, (err, entries) => { | |
for(let entry of entries) { | |
fs.stat( | |
path.join(dir, entry), | |
self._onStat(path.join(dir, entry)) | |
); | |
} | |
}); | |
} | |
_onStat(entry) { | |
let self = this; | |
return (err, stat) => { | |
if(!stat) return; | |
if(stat.isDirectory()) return self._find(entry); | |
if(stat.isFile() && path.basename(entry) == self._filename) { | |
self.emit('match', entry); | |
} | |
} | |
} | |
run() { | |
this._find(this._dir); | |
} | |
} | |
module.exports = FileSearch; |
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
const | |
FileSearch = require('./FileSearch.js'); | |
// let's look for 'index.js' files in '~/Projects' (ex.: /Users/num8er/Projects) | |
let fileSearch = new FileSearch('index.js', '~/Projects'); | |
fileSearch.on('match', (file) => { | |
console.log('Found file:', file); | |
}); | |
fileSearch.run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment