Last active
March 4, 2016 07:41
-
-
Save chrisyip/601cd49a07a0e04520f0 to your computer and use it in GitHub Desktop.
Batch module loader for 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
'use strict' | |
const addtionalExts = [] | |
const fs = require('fs') | |
const path = require('path') | |
function find (root, p, re, recursive) { | |
if (root) { | |
p = path.resolve(root, p) | |
} | |
let result = fs.readdirSync(p) | |
let results = [] | |
result.forEach(np => { | |
np = path.resolve(p, np) | |
let stats = fs.statSync(np) | |
if (stats.isFile()) { | |
if (re.test(np)) { | |
results.push(require(np)) | |
} | |
} else if (stats.isDirectory()) { | |
if (recursive) { | |
results.concat(find(np, re, recursive)) | |
} else { | |
results.push(require(np)) | |
} | |
} | |
}) | |
return results | |
} | |
module.exports = (root, paths, recursive) => { | |
if (typeof paths !== 'string' && !Array.isArray(paths)) { | |
recursive = paths | |
paths = root | |
root = null | |
} | |
if (!Array.isArray(paths)) { | |
paths = [paths] | |
} | |
let exts = Object.keys(require.extensions) | |
exts = exts.concat(addtionalExts) | |
let re = new RegExp(`(?:${exts.join('|').replace(/\./g, '\\.')})$`) | |
let results = [] | |
paths.forEach(path => results = results.concat(find(root, path, re, recursive))) | |
return results | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment