Last active
December 23, 2015 13:29
-
-
Save fiveisprime/6642631 to your computer and use it in GitHub Desktop.
Walk a directory recursively but in order from top to bottom to find the specified file synchronously.
This file contains hidden or 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 fs = require('fs') | |
| , path = require('path'); | |
| function find(dir, search, exclude) { | |
| var full = null | |
| , stat = null | |
| , directories = [] | |
| , directory, contents, i, j; | |
| exclude = exclude || []; | |
| if (!fs.existsSync(dir)) return null; | |
| if (fs.statSync(dir).isFile()) { | |
| if (dir === search) return dir; | |
| return null; | |
| } | |
| contents = fs.readdirSync(dir); | |
| for (i = 0; i < contents.length; i++) { | |
| if (exclude.indexOf(contents[i]) >= 0) continue; | |
| full = path.join(dir, contents[i]); | |
| stat = fs.lstatSync(full); | |
| if (stat.isSymbolicLink()) continue; | |
| if (stat.isDirectory()) { | |
| directories.push(full); | |
| continue; | |
| } | |
| if (contents[i] === search) return full; | |
| } | |
| while (directory = directories.pop()) { | |
| contents = fs.readdirSync(directory); | |
| for (j = 0; j < contents.length; j++) { | |
| if (exclude.indexOf(contents[j]) >= 0) continue; | |
| full = path.join(directory, contents[j]); | |
| stat = fs.lstatSync(full); | |
| if (stat.isSymbolicLink()) continue; | |
| if (stat.isDirectory()) { | |
| directories.push(full); | |
| continue; | |
| } | |
| if (contents[j] === search) return path.join(directory, contents[j]); | |
| } | |
| } | |
| return null; | |
| } | |
| var found = find(process.argv[2], process.argv[3], process.argv[4]); | |
| console.log('found', found); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Made this into a module
https://github.com/fiveisprime/find-file-sync