Home > OS >  I keep seeing await require is OK, but I cannot make it work
I keep seeing await require is OK, but I cannot make it work

Time:08-06

Ok, so there are answers here such as this one that state that I should be able to export a promise and then await on said promise whenever I require the module. Well, I cannot make it work. I always get the error message SyntaxError: await is only valid in async functions and the top level bodies of modules. But guess what: As far as I can tell I am putting in at the top level of a module!

Here's some code:

const wjConfig = require('wj-config');
const fs = require('fs');

const loadJsonFile = (fileName, isRequired) => {
    const fileExists = fs.existsSync(fileName);
    if (fileExists) {
        const data = fs.readFileSync(fileName);
        return JSON.parse(data);
    }
    else if (isRequired) {
        throw new Error(`Configuration file ${fileName} is required but was not found.`);
    }
    // Return an empty object.
    return {};
};

const env = new wjConfig.Environment(process.env.NODE_ENV);
const config = wjConfig()
    .addObject(loadJsonFile('./config/config.json', true))
    .name('Main Configuration')
    .addObject(loadJsonFile(`./config/config.${env.value}.json`))
    .name('Env Configuration')
    .addEnvironment(process.env)
    .includeEnvironment(env)
    .createUrlFunctions()
    .includeValueTrace()
    .build();

// Is this not part of the top level of this module??
module.exports = await config;

I have also done const config = await wjConfig() with the same result.

I have also tried removing await from this config.js module and putting it in the main entry point file index.js. Same error. Bottomline: No matter where I put the await, I cannot make this work. Any pointers?

I am using NodeJS v18.1.0. Many thanks.

CodePudding user response:

At the top level, you can only use await in ESM modules (that use import not require()), not in CommonJS modules which is what your code is.

So, as long as your code is in a CommonJS module, you can't use await at the top level.

As for the error message:

SyntaxError: await is only valid in async functions and the top level bodies of modules

That is indeed not entirely clear. Apparently when they say "modules", they mean type: "module" as one would specify it in package.json which is an ESM module, not a CommonJS module.

It could also be that this error message is from the V8 JS engine where the error messages are targeted more at the browser environment where the only type of Javascript "module" in the browser is an ESM module as there is no other type of "module" in a browser.

  • Related