Node.js调用Google Sheets服务账户时keyfilePath路径错误求助
解决Node.js访问Google Sheets时"Cannot find module './key.json'"错误
我尝试编写Node.js脚本通过Service Account认证访问Google Sheets数据,但运行时始终报错:
Error: Cannot find module './key.json'
已确认服务账户JSON文件路径正确(文件层级结构显示key.json与脚本同级),且重新下载文件排除损坏问题,但错误依旧。附上代码:
const { google } = require("googleapis"); const { authenticate } = require("@google-cloud/local-auth"); const spreadsheetId = "1ZxZ0kghl5GueyQgTVMILyfsHVFgXPMZT6_qlt1oPBZA"; const range = "Sheet1!A1:D10"; // Create a Google Sheets client const sheets = google.sheets({ version: "v4", }); // Authenticate the client authenticate({ keyfilePath: "./key.json", scopes: ["https://www.googleapis.com/auth/spreadsheets"], }).then((credentials) => { sheets.auth = credentials; // Get the data from the Google Sheets doc sheets.spreadsheets.values .get({ spreadsheetId, range, }) .then((response) => { const data = response.data.values; // Print the data console.log(data); }); });
排查与解决方案
确认脚本执行路径
你可能在脚本所在目录之外的路径执行node命令。比如脚本在/project/src目录,却在/project下运行node src/script.js,此时./key.json会指向/project/key.json而非/project/src/key.json。
解决:切换到脚本所在目录执行命令,或使用基于__dirname的绝对路径:const path = require('path'); // ... authenticate({ keyfilePath: path.join(__dirname, 'key.json'), scopes: ["https://www.googleapis.com/auth/spreadsheets"], })检查文件名大小写
Linux/macOS系统对文件名大小写敏感,确认文件是key.json而非Key.json或KEY.JSON。验证文件实际存在性
在脚本所在目录执行ls(Linux/macOS)或dir(Windows)命令,确认key.json确实在目录中——文件管理器可能存在缓存,命令行结果更准确。注意库的路径解析逻辑
@google-cloud/local-auth的keyfilePath参数是相对于当前工作目录,而非脚本文件目录,这是常见坑点。用__dirname拼接路径能彻底避免这个问题,因为__dirname始终指向当前脚本所在目录。
修正后的完整代码
const { google } = require("googleapis"); const { authenticate } = require("@google-cloud/local-auth"); const path = require('path'); const spreadsheetId = "1ZxZ0kghl5GueyQgTVMILyfsHVFgXPMZT6_qlt1oPBZA"; const range = "Sheet1!A1:D10"; const sheets = google.sheets({ version: "v4", }); authenticate({ keyfilePath: path.join(__dirname, 'key.json'), scopes: ["https://www.googleapis.com/auth/spreadsheets"], }).then((credentials) => { sheets.auth = credentials; sheets.spreadsheets.values .get({ spreadsheetId, range, }) .then((response) => { const data = response.data.values; console.log(data); }) .catch(err => console.error('获取数据失败:', err)); // 添加错误捕获,便于排查后续问题 });
内容的提问来源于stack exchange,提问作者Laplace's Code
相关产品推荐
相关产品推荐

