Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda