0

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?

vy218
  • 707
  • 1
  • 8
  • 15
  • Can you supply details of the problem being solved? For example, why not create an index module that requires all the class constructor scripts and puts their source paths and export objects in an array that the index module exports? Or simply require the class files in the modules that use them? In regards the linked previous question, `require` is a synchronous process (in node.js at least) and does not inherently need to be wrapped in a promise. – traktor Feb 06 '22 at 01:31
  • I don't understand what you mean by "*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.*". Can you please include the code that you tried into your question? – Bergi Feb 06 '22 at 02:45
  • @traktor thanks for the reply - Using an index file probably isn’t going to be possible. Each file in the directory gets transformed into an HTML page, and so if I stick extra files in the directory, I will get extra HTML files created, which I don’t want. It would mean creating HTML files called index would no longer be possible. – vy218 Feb 07 '22 at 02:45
  • @Bergi thanks - the code is in the linked SO question. I found that using require only worked when it was right at the start. Anywhere else and the data was not loaded by the time the subsequent code was trying to access it. – vy218 Feb 07 '22 at 02:48
  • Have you written anything to walk a directory tree from its root and create an index of filepaths to javascript files encountered during traversal? _Even if this is not what you want to do_, please update the question clarifying the problem to be solved and details of the code you have tried so far. – traktor Feb 07 '22 at 10:44

0 Answers0