Skip to content

Instantly share code, notes, and snippets.

@sshaplygin
Last active January 18, 2019 11:19
Show Gist options
  • Save sshaplygin/af2966b626dd1c9b92f37982bd7e787f to your computer and use it in GitHub Desktop.
Save sshaplygin/af2966b626dd1c9b92f37982bd7e787f to your computer and use it in GitHub Desktop.
load files from directory and subdirectiry in nodejs
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);
}
// index where is requery module
module.exports = require('../utils/loadModules')(__dirname);
// ../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