Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

146
Views
How to load javascript modules into an array?

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!