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

137
Views
Express is listening before glob is done going through route files

in my js classes i have routes for express to use in the route property

my problem is that express starts listening before the routes are done loading via glob:

glob("pages/**/*.js", (error, file) => {
  import("./" + file).then((page) => {
    console.log(new page.default().route);
  });
});

app.listen(config.port, () =>
  console.log(`App listening on http://localhost:${config.port}`)
);

here is my console output:

node index.js
App listening on http://localhost:1337
{ uri: '/users' }

notice how the uri line comes AFTER app listening when it should be before

i've also tried using glob.sync and the same thing happens

how do i make the code wait for the route files to finish loading before app.listen fires?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can solve this with glob.sync.

const pages = glob("pages/**/*.js")

for (pageName of pages) {
  const page = await import("./" + pageName)
  console.log(new page.default().route)
}

app.listen(config.port, () =>
  console.log(`App listening on http://localhost:${config.port}`)
)

Because import() is asynchronous, it returns a Promise, which you are waiting for using .then(...), which isn't blocking. By using await, the code waits for the module to be imported.

You will need to do this in an environment, that either supports top level await, or inside an asynchronous function. Example:

async function startApp() {
 // const pages = ...
}
startApp()

Read more about promises here: https://www.w3schools.com/js/js_promise.asp

about 4 years ago · Juan Pablo Isaza Report
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!