ModuleSystem.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. const fs = require('fs');
  2. const path = require('path');
  3. const Module = require('../base/Module');
  4. const RepositorySystem = require('./RepositorySystem');
  5. class ModuleSystem {
  6. constructor() {
  7. this.modules = [];
  8. this.instances = [];
  9. this.loadedModules = [];
  10. }
  11. run() {
  12. this.instances = this.modules.map((mod) => new mod());
  13. this.loadedModules = [...this.loadedModules, ...this.modules];
  14. this.modules = [];
  15. }
  16. loadModule(mod) {
  17. mod.__loadedDirectory = "imported/" + mod.name;
  18. this.modules.push(mod);
  19. console.log("File ", mod.__loadedDirectory + ' loaded successfully');
  20. }
  21. loadModules(filepath = 'modules', prefix="") {
  22. // search files
  23. let p = path.resolve(filepath);
  24. let current = [];
  25. console.log("Filepath:", p);
  26. let files = fs.readdirSync(p);
  27. for(var ind in files) {
  28. let filename = files[ind];
  29. try {
  30. let temp = require(path.resolve(filepath, filename));
  31. if(temp.prototype instanceof Module) {
  32. temp.__loadedDirectory = filepath + '/' + filename;
  33. current.push(temp);
  34. }
  35. } catch(e) {
  36. let err = "Cannot read file -> " + filepath + '/' + filename;
  37. console.log(err);
  38. throw e;
  39. }
  40. }
  41. console.log('Modules Loaded:');
  42. for(var i in current) {
  43. console.log("File ", current[i].__loadedDirectory + ' loaded successfully');
  44. }
  45. this.modules = [
  46. ...this.modules,
  47. ...current
  48. ];
  49. }
  50. }
  51. module.exports = new ModuleSystem();