alexa-skills-kit - 从 s3 读取数据:s3.getObject 不是函数
问题描述
我正在尝试从 S3 读取一个 txt 文件来为 Alexa 构建响应。在 Lambda 中测试代码时,我收到此错误。谁能看到我哪里出错了?
错误
Error handled: s3.getObject is not a function
我已经安装了“aws-sdk”并需要在我的技能 index.js 顶部的模块
const s3 = require('aws-sdk/clients/s3')
处理程序代码。只是为了强调这一点,我正在使用 Async/Await 并在下面的 goGetS3 函数中返回一个 Promise。
const ChooseStoryIntentHandler = {
canHandle(handlerInput) {
return handlerInput.requestEnvelope.request.type === 'IntentRequest' &&
handlerInput.requestEnvelope.request.intent.name === 'ChooseStoryIntent';
},
async handle(handlerInput) {
let speechText;
let options = {
"Bucket": "stores",
"Key": "person.txt"
}
await goGetS3(options)
.then((response) => {
console.log(response),
console.log(response.Body.toString()),
speechText = response
})
.catch((err) => {
console.log(err)
speechText = 'something wrong getting the story'
})
return handlerInput.responseBuilder
.speak(speechText)
.reprompt(speechText)
.getResponse();
},
};
goGetS3() 函数代码。我尝试了它的两个不同版本,都给了我上面相同的错误。
const goGetS3 = function (options) {
s3.getObject(options, function (err, data) {
//handle error
if (err) {
reject("Error", err);
}
//success
if (data) {
resolve(data.Body.toString())
}
}).promise()
}
// const goGetS3 = function (options) {
// return new Promise((resolve, reject) => {
// s3.getObject(options, function (err, data) {
// //handle error
// if (err) {
// reject("Error", err);
// }
// //success
// if (data) {
// resolve(data.Body.toString())
// }
// })
// })
// }
我的代码是从以下博客/文章中组装而成的。
- 使用 ask new cli 的 hello-world 技能模板
- https://github.com/aws/aws-sdk-js/issues/1436
- https://stackoverflow.com/questions/36942442/how-to-get-response-from-s3-getobject-in-node-js
-
https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/S3.html
#### 编辑 ###
根据@milan-cermak,我在页面顶部添加了这个
const AWS = require('aws-sdk/clients/s3')
const s3 = new AWS.S3()
但现在得到这个错误
module initialization error: TypeError
at Object.<anonymous> (/var/task/index.js:6:12)
at Module._compile (module.js:652:30)
at Object.Module._extensions..js (module.js:663:10)
at Module.load (module.js:565:32)
at tryModuleLoad (module.js:505:12)
at Function.Module._load (module.js:497:3)
at Module.require (module.js:596:17)
at require (internal/module.js:11:18)
解决方案
您的s3
代码中的不是 S3 客户端的实例,而只是模块。您需要首先创建客户端的新实例。
const S3 = require('aws-sdk/clients/s3');
const s3 = new S3();
// you can now do s3.getObject
推荐阅读
- unity3d - 警告 CS0642,可能是错误的空语句
- node.js - AdonisJS 无法在函数内返回响应(SAP HANA)
- angular - Angular - mat-autocomplete 到 mat-select-search
- flutter - 隐藏溢出颤动,没有溢出消息
- reactjs - 如何遍历 MongoDB 条目,总结条目并呈现在 React 前端
- elasticsearch - 是否支持星号以外的 ElasticSearch 索引模式通配符?
- keras - 如何在 Keras 更改 ImageDataGenerator 的预处理函数执行顺序?
- rust - 将可变实例方法传递给函数
- javascript - React Router 在构建到 ftp 服务器后不渲染组件
- android - Android Studio Admob 错误属性未知