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?
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