troygoode / node-require-directory

Recursively iterates over specified directory, requiring each file, and returning a nested hash structure containing those libraries.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

ECMAScript modules example

brandonros opened this issue · comments

Might make sense to put one in the README?

Does this package work with the Node 14 ESM implementation at all?

export const initRoutes = async (app) => {
  const __filename = url.fileURLToPath(import.meta.url)
  const __dirname = path.dirname(__filename)
  const filenames = glob.sync(path.resolve(__dirname + '/../routes/**/*.mjs'))
  for (let i = 0; i < filenames.length; ++i) {
    const filename = filenames[i]
    const { default: route } = await import(filename)
    app[route.method](
      route.path,
      buildRequestIdMiddleware(),
      buildRequestLoggerMiddleware(),
      buildRateLimitMiddleware(route),
      buildAsyncRouteHandlerMiddleware(route),
      buildResponseLoggerMiddleware()
    )
  }
}

probably not. i abandoned trying to use it it and did this.

I came across this issue today where I wanted to use ES6 imports which this package doesn't support.
My use case was initializing routes/middlewares on app start. So I made a simple alternative that lets me use the visit and include options like this package but with ESM. Works well with top-level await.
Here's an example