首页 > 解决方案 > 从 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())
//       }
//     })
//   })
// }

我的代码是从以下博客/文章中组装而成的。

#### 编辑 ###

根据@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)

标签: alexa-skills-kit

解决方案


您的s3代码中的不是 S3 客户端的实例,而只是模块。您需要首先创建客户端的新实例。

const S3 = require('aws-sdk/clients/s3');
const s3 = new S3();

// you can now do s3.getObject

推荐阅读