TS1309
TS1309: The current file is a CommonJS module and cannot use 'await' at the top level.
Broken Code ❌
const response = await youtube.playlistItems.list({
part: ['snippet'],
playlistId,
});Solution:
This error occurs because top-level await is only supported in ECMAScript modules, not in CommonJS modules which are the default module system in Node.js unless specified otherwise.
To use top-level await, you need to configure your project to use ECMAScript modules by adding "type": "module" to your package.json. This tells Node.js to treat all code files as ECMAScript modules.
Fixed Code ✔️
{
"name": "your-package-name",
"version": "1.0.0",
"type": "module"
}Another Solution:
To work around the restriction of not using await at the top level in a CommonJS module, you can also encapsulate your asynchronous operations within an Immediately Invoked Function Expression (IIFE) that is async:
(async () => {
const response = await youtube.playlistItems.list({
part: ['snippet'],
playlistId,
});
console.log(response.data.items);
})();