I have a directory tree that contains javascript files which each export a class. I need to load all these modules into an array that maps to how these files are organised on the file system:
For example:
// rootDir/fileA.js
module.exports = class A { … }
// rootDir/subDir/fileB.js
module.exports = class B { … }
—->
[
{
path: ‘rootDir/fileA.js’,
value: class A { … }
},
{
path: ‘rootDir/subDir/fileB.js’,
value: class B { … }
}
]
Ideally they would be loaded into an array with the above structure. The directory tree could have many files organised in any way possible.
I’ve tried doing this using require, but since it’s synchronous, that only works if I run it at the very top of my code. When I run it at a lower level, the subsequent code executes before all the modules are loaded, and so errors because the classes aren’t there when I try to use them.
Previous question that documents what I tried for a similar but different use case:
How to require directories using async / await
How can I create the array of class objects in a way that my code can use the loaded modules?