Last active
January 18, 2019 11:19
-
-
Save sshaplygin/af2966b626dd1c9b92f37982bd7e787f to your computer and use it in GitHub Desktop.
load files from directory and subdirectiry in nodejs
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
module.exports = (filePath) => { | |
const dirPathArr = filePath.split('/'); | |
const targerFile = dirPathArr[dirPathArr.length - 1]; | |
const dotIndex = targerFile.indexOf('.'); | |
return targerFile.slice(0, dotIndex > -1 ? dotIndex : targerFile.length); | |
} |
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
// index where is requery module | |
module.exports = require('../utils/loadModules')(__dirname); |
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
// ../utils/loadModules.js | |
const fs = require('fs'); | |
const path = require('path'); | |
const getFileName = require('./getFileName'); | |
const defaultFilter = ['index']; | |
function loadModule (modulePath, filter) { | |
const files = fs.readdirSync(modulePath); | |
const modules = {}; | |
if (filter === undefined) { | |
filter = defaultFilter; | |
} | |
const ignoredFileNames = new Set(filter); | |
files.forEach((file, fileIndex) => { | |
const filePath = path.join(modulePath, file); | |
const fileName = getFileName(filePath); | |
if (fs.statSync(filePath).isDirectory()) { | |
modules[fileName] = loadModule({ modulePath: filePath }); | |
} else { | |
if (!ignoredFileNames.has(fileName)) { | |
modules[fileName] = require(path.join(modulePath, fileName)); | |
} | |
} | |
}); | |
return modules; | |
}; | |
module.exports = loadModule; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment