Skip to content

Instantly share code, notes, and snippets.

@robinmollah
Created September 23, 2021 18:23
Show Gist options
  • Save robinmollah/e41a9f62c073b9e9295814a952c2d6ab to your computer and use it in GitHub Desktop.
Save robinmollah/e41a9f62c073b9e9295814a952c2d6ab to your computer and use it in GitHub Desktop.
Looks for `searchQuery` subdirectory in `folder`
const fs = require("fs");
const path = require("path");
function findFolder(folder, searchQuery) {
if (!fs.existsSync(folder)) {
console.error("dir not found ", folder);
return;
}
let subdirs = fs
.readdirSync(folder, { withFileTypes: true })
.filter((cont) => cont.isDirectory())
.map((cont) => cont.name);
if (subdirs.length) {
let searchIndex = subdirs.indexOf(searchQuery);
if (searchIndex > -1) {
const absolutePath = path.join(
path.resolve(folder),
subdirs[searchIndex]
);
return [absolutePath];
}
for (let subdir of subdirs) {
let sub = findFolder(path.join(folder, subdir), searchQuery);
if (sub.length) {
return sub;
}
}
return [];
} else {
return [];
}
}
const searchResult = findFolder("./", "is-stream")[0];
console.log(searchResult);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment