// addons.ts
export interface addon {
name: string;
desc: string;
run: (someparam: any) => void;
}
export function loadaddons(): Array<addon> {
let addons: Array<addon> = [];
fs.readdirSync(path.join(__dirname, "addons"))
.filter((file) => file.endsWith(".js"))
.forEach((file) => {
import(path.join(__dirname, "addons", file)).then((imported) => {
addons.push({
name: imported.addonInfo.name,
desc: imported.addonInfo.desc,
run: imported.startAddon,
});
});
});
return addons;
}
// index.ts
import { loadaddons } from "./addons";
let addons = loadaddons();
addons.forEach((addon) => {
addon.run("someparam");
});
// example addon
export const addonInfo = {
name: "exampleaddon",
desc: "an example addon",
};
export function startAddon() {}
// output
[]
// wanted output
[
{
name: 'exampleaddon',
desc: 'an example addon',
run: [Function: startAddon]
}
]
There is an issue regarding the asynchronous behavior of the import() function. The function does not wait for all addons to be imported and added before returning, causing incomplete results. Here is how I want the process to run:
- Read directory
- Filter files with .js extension
- Cycle through each file asynchronously
- Import addon
- Add info to addons variable
- Return the complete addons array
Note that I am new to TypeScript.