Skip to content
Advertisement

Import and execute all files on folder with es6

I am migrating some node ES5 node code to Typescript. I need to port these two pieces of code where I iterate through all the files in a directory and call the default function these files are exporting. How would I do that in Typescript or ES6?

models/index.js

const fs = require("fs");

module.exports = () =>
  fs.readdirSync(__dirname).map((model) => {
    if (model === "index.js") return;
    return require("./" + model);
  });

index.js

const modelDefiners = require("./models")();

for (const modelDefiner of modelDefiners) {
  if (typeof modelDefiner === "function") {
    modelDefiner();
  }
}

Advertisement

Answer

You can do this with dynamic imports:

import { promises as fs } from 'fs';
import { join } from 'path';

export default async function*() {
  for (const model of await fs.readdir(__dirname)) {
    if (model === "index.js") continue;
    yield await import(join(__dirname, model));
  }
}
import modelDefiners from "./models";

(async () => {
  for await (const {default: modelDefiner} of modelDefiners()) {
    if (typeof modelDefiner === "function") {
      modelDefiner();
    }
  }
})();
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement