Skip to content

Instantly share code, notes, and snippets.

@DarkSeraphim
Created March 18, 2019 15:38
Show Gist options
  • Save DarkSeraphim/c1cd86b542815493b4ba72346bd8f4c1 to your computer and use it in GitHub Desktop.
Save DarkSeraphim/c1cd86b542815493b4ba72346bd8f4c1 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const path = require('path');
function getStat(path) {
try {
return fs.statSync(path);
} catch (e) {
return null;
}
}
function fileExists(path) {
let stat = getStat(path);
return stat && stat.isFile();
}
function directoryExists(path) {
let stat = getStat();
return stat && stat.isDirectory();
}
function* load(directory) {
let index = path.join(directory, 'index.js');
// If index.js exists in the directory, halt recursion
// and let index.js do the rest of the subtree
if (fileExists(index)) {
yield index;
return;
}
// Otherwise, load all JS files in the directory, and scan all directories
let children = fs.readdirSync(directory);
for (let child of children) {
let node = path.join(directory, child);
if (node.endsWith(".js") && fileExists(node)) {
yield node;
} else if (directoryExists(node)) {
for (let file of load(node)) {
yield file;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment