node.js - 如何在 nodejs 中使用谷歌电子表格
问题描述
我想使用 google-spreadsheet API 来获取数据并将数据写入我的 Discord 机器人中的工作表(使用 discord.js)。出于某种原因,我无法让它工作。这是我的代码:
const { GoogleSpreadsheet } = require('google-spreadsheet')
const creds = require('../service-account.json')
module.exports = {
/...
execute(message, args) {
accessSpreadsheet()
}
}
async function accessSpreadsheet() {
const doc = new GoogleSpreadsheet('<id was here>')
doc.useServiceAccountAuth(creds)
.then(() => {
doc.getInfo()
.then(info => {
console.log(`Loaded doc: ` + info.title + ` by ` + info.author.email)
const sheet = info.worksheets[0]
console.log(
`sheet 1: ` + sheet.title + ` ` + sheet.rowCount + `x` + sheet.colCount
)
})
})
}
这是我不断收到的错误:
(node:4) UnhandledPromiseRejectionWarning: Error: Google API error - [404] Requested entity was not found.
at createError (/app/node_modules/axios/lib/core/createError.js:16:15)
at settle (/app/node_modules/axios/lib/core/settle.js:17:12)
at IncomingMessage.handleStreamEnd (/app/node_modules/axios/lib/adapters/http.js:236:11)
at IncomingMessage.emit (events.js:327:22)
at endReadableNT (_stream_readable.js:1221:12)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:4) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 3)
(node:4) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
解决方案
我实际上应该使用 async/await 来实现这一点。我的代码变成了:
async function accessSpreadsheet(message, args, msg) {
const doc = new GoogleSpreadsheet('<id was here>')
await doc.useServiceAccountAuth(creds)
await doc.loadInfo()
console.log(doc.title) //whatever you want to log goes here
})
推荐阅读
- windows-mixed-reality - 如果文本转语音过多,我的 HoloLens 2 会关闭
- reactjs - 更改 React 材料表中的 addNewRow 图标位置
- scala - 在函数中使用 ADT 的参数化分支
- html - 将 `nth-of-type` 应用于某个类无法正常工作
- json - URL 查询字符串不起作用!我该如何解决?
- c# - 虚拟助手无法发送新的 QnA maker 知识库
- javascript - 为什么在我解析出时区后时间戳日志落后了一天?
- typescript - 当我只有 TurnContext 时,如何在 Microsoft Bot Framework v4 中获取调用者的 TenantID?
- node.js - Heroku 部署因非必需节点模块而崩溃
- c++ - 如何防止双精度值到整数的隐式转换