7
votes

Is top-level await still not supported in Node.js (Jan 2020, Node.js 13.5.0)?

I've tried some tutorials, like this one, but still no luck, always getting the same error:

D:\NodeJS>node --experimental-modules test.js
(node:17724) ExperimentalWarning: The ESM module loader is experimental.
file:///D:/NodeJS/test.js:9
await test();
^^^^^

SyntaxError: Unexpected reserved word

The entire file content:

function test() {
}

await test();

I have tried using "type": "module" in package.json, and renaming file into test.mjs, but still the same error, even with the latest Node.js 13.5.0

What am I doing wrong?

5
top-level await is still a stage 3 proposal, what makes you think it's an experimental feature in node? - Klaycon
The article you refer to only talks about ES modules, not top level await - pietrovismara
that article describes enabling ES modules, which have been in the spec for a while, not top-level await which is still a proposal - Klaycon
@Klaycon As I explained, I did try renaming the file to *.mjs, and setting type to module, but none worked. Those things were supposed to turn the script into ES module. - vitaly-t
Then why is your question about top level await?? I think you are mixing up 2 separate topics. - pietrovismara

5 Answers

11
votes

Per this issue tracker and this blog post, top-level await is available in Node v13.3+ behind the flag --harmony-top-level-await. The module flag you're enabling is only for ESM modules and not for top level await.

3
votes

node --experimental-repl-await works for the Node REPL

2
votes

I dont know why, but to get the --harmony features like you need to use --eval (-e) or --print (-p) instead of just launching node like node -e "import('./test.mjs')" --experimental-modules --input-type=module --harmony-top-level-await

file-content:

console.log(await Promise.resolve("test"));

console:

node -e "import('./test.mjs')" --experimental-modules --input-type=module --harmony-top-level-await
(node:9096) ExperimentalWarning: The ESM module loader is experimental.
test

1
votes

When using node -e:

Note that while top-level await is unflagged in node 14.8.0, when doing node -e (node --eval), the input type defaults to CJS, and top-level await is allowed only in ESM mode.

To tell that the input is ESM, you need a flag:

node --input-type=module -e 'console.log(await Promise.resolve(42))'
> 42
-8
votes

I think you are missing the async annotation

async function test() {
}

await test();