0

I have the following function:

export default async function getController() {
    const directoryPath = path.join(__dirname, '@presentation/controller');

    let controller = [];
    await fs.readdir(directoryPath, async (err, files) => {
    if (err) {
        return console.log('Unable to scan directory: ' + err);
    }

    for (let file of files) {
        const fullPath = path.join(directoryPath, file);
        if (path.extname(fullPath) === '.ts') {
            try {
                const module = await import(fullPath);
                controller.push(module.default);
            } catch (err) {
                console.log('Erro ao importar o módulo:', err);
            }
        }
    }
    });
    return controller
}

When I try to call the function in another file like this:

const controllers = await getController();

I get the error:

ReferenceError: await is not defined

My tsconfig looks like this:

{
  "compilerOptions": {
    "module": "Node16",
    "target": "es2017",
    ...
}

I tried changing tsconfig settings I've also tried changing the way the function is exported by throwing it in a variable, however I just got a different error.

InSync
  • 4,851
  • 4
  • 8
  • 30
  • 1
    Does this answer your question? [await is only valid in async function](https://stackoverflow.com/questions/49432579/await-is-only-valid-in-async-function) – InSync Jul 21 '23 at 22:19
  • No because the function I'm calling is asynchronous – Aurelio Moreira Jul 21 '23 at 22:30
  • Is your `const controllers = ...` code within an async function? – JSmart523 Jul 22 '23 at 06:02
  • yes, it is defined as async function getController() – Aurelio Moreira Jul 22 '23 at 11:45
  • @AurelioMoreira Do you call `getController` inside an async function? If no, you need to make sure your tsc configuration supports "top level await" feature. Or you could wrap your code `async function run() { const controllers = await getController(); // rest of your logic }; run().catch(console.error)` – Yury Tarabanko Jul 22 '23 at 12:04
  • @YuryTarabanko This solved it in parts, I changed the tsconfig.json "module": "esnext" and the package.json "type": "module" and now it is generating the error TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" – Aurelio Moreira Jul 22 '23 at 15:11
  • @AurelioMoreira The new problem is not related to the original question. You can use error name "ERR_UNKNOWN_FILE_EXTENSION" to google for possible solutions. After you solve the extension issue your next question will likely be about why your `controller` array is empty. – Yury Tarabanko Jul 22 '23 at 17:08

0 Answers0