The complicated answer is: because of the differences between versions 16 and 18 of node.js, and I don't know them all. In version 16, I think what I quote from nodejs.org below does not apply. Also, I tried the extensions cjs and mjs, and node.js v16 will not load a module with require()
and needs import
instead, but import
can only be used from within a module, if I remember my research correctly.
The simple answer is that I was using the wrong version of node.js.
Someone thought the answer was the difference between .js and .mjs (and provided a question about those differences), but that wasn't it. I was not able to answer my own question because it has been closed, but hopefully this edit takes and proves valuable to someone else who tries to use v18 documentation with v16 code.
In mid-October, 2022, https://nodejs.org/api/modules.html#modules-commonjs-modules says (about node.js 18, not node.js 16, which I am using) "In Node.js, each file is treated as a separate module." I have this code which produces the error "SyntaxError: await is only valid in async functions and the top level bodies of modules"
init.js
module.exports.TESTING = (process.argv[2] == 'test');
async function init() {
let ss = require('./safestore.js');
let p = await ss.safestore.read();
return p;
}
await init();
it.js
require('./init.js');
... when I run node it.js test
If I change the last line of init.js to (async () => { await init(); })();
then it works fine, hence fulfilling the "in async functions" part of the error, but apparently, node.js is not treating the file init.js as a separate module. Why isn't it?