javascriptnode.jsasync-awaitnpm-packagegenius-api

node-genius-lyrics: await is only valid in async functions and the top level bodies of modules


I am running the example code given from node-genius-lyrics after installing the package through npm

const Genius = require("genius-lyrics");
const Client = new Genius.Client(myClientID);

const searches = await Client.songs.search("faded");

// Pick first one
const firstSong = searches[0];
console.log("About the Song:\n", firstSong, "\n");

// Ok lets get the lyrics
const lyrics = await firstSong.lyrics();
console.log("Lyrics of the Song:\n", lyrics, "\n");

But error occur:

const searches = await Client.songs.search("faded");
                 ^^^^^

SyntaxError: await is only valid in async functions and the top level bodies of modules
    at internalCompileFunction (node:internal/vm:73:18)
    at wrapSafe (node:internal/modules/cjs/loader:1153:20)
    at Module._compile (node:internal/modules/cjs/loader:1205:27)
    at Module._extensions..js (node:internal/modules/cjs/loader:1295:10)
    at Module.load (node:internal/modules/cjs/loader:1091:32)
    at Module._load (node:internal/modules/cjs/loader:938:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:83:12)
    at node:internal/main/run_main_module:23:47

Node.js v20.9.0

May I know how to fix this error? Any help would be appreciated.


Solution

  • Top level await is only supported in esm module they won't work in commonjs module (default nodeJS module type).

    Either change your code to esm by changing "type": "module" in your package.json or warp the code into a async function like below.

    1. Using async function for commonjs module

       async function getSongs() {
           const searches = await Client.songs.search('faded');
      
           // Pick first one
           const firstSong = searches[0];
           console.log('About the Song:\n', firstSong, '\n');
      
           // Ok lets get the lyrics
           const lyrics = await firstSong.lyrics();
           console.log('Lyrics of the Song:\n', lyrics, '\n');
       }
      
       getSongs();
      
    2. Changing into ESM module

      By default nodeJS in commonjs, create a property type in package.json and set value as module

      {
          "type": "module"
      }
      

      Then use import statement instead of require

      import Genius from 'genius-lyrics';
      
      const Client = new Genius.Client(myClientID);
      
      const searches = await Client.songs.search('faded');
      
      // Pick first one
      const firstSong = searches[0];
      console.log('About the Song:\n', firstSong, '\n');
      
      // Ok lets get the lyrics
      const lyrics = await firstSong.lyrics();
      console.log('Lyrics of the Song:\n', lyrics, '\n');