使用node-genius-lyrics时遇await语法错误,求解决方法
修复
await is only valid in async functions and the top level bodies of modules错误 这个错误的核心原因是你当前代码运行在CommonJS模块环境(Node.js默认的模块系统)中,await关键字不能直接在代码顶层使用,必须包裹在async函数内部;或者你可以切换到ES模块环境来支持顶层await。
以下是两种可行的修复方案:
方案1:用async函数包裹代码
将所有使用await的逻辑放到一个异步函数中,同时添加错误处理避免未捕获异常:
const Genius = require("genius-lyrics"); const Client = new Genius.Client(myClientID); // 定义异步主函数 async function fetchLyrics() { try { const searches = await Client.songs.search("faded"); const firstSong = searches[0]; console.log("About the Song:\n", firstSong, "\n"); const lyrics = await firstSong.lyrics(); console.log("Lyrics of the Song:\n", lyrics, "\n"); } catch (error) { console.error("获取歌词时出错:", error); } } // 执行函数 fetchLyrics();
方案2:切换到ES模块环境支持顶层await
方法A:修改文件后缀为.mjs
把代码文件后缀从.js改成.mjs,同时替换模块导入语法:
import Genius from "genius-lyrics"; const Client = new Genius.Client(myClientID); // 直接在顶层使用await const searches = await Client.songs.search("faded"); const firstSong = searches[0]; console.log("About the Song:\n", firstSong, "\n"); const lyrics = await firstSong.lyrics(); console.log("Lyrics of the Song:\n", lyrics, "\n");
方法B:在package.json中声明ES模块
在项目根目录的package.json中添加"type": "module"字段:
{ "type": "module" }
之后你的.js文件会被当作ES模块处理,替换require为import后,即可直接使用顶层await。
内容的提问来源于stack exchange,提问作者streetlight006
相关产品推荐
相关产品推荐

