【问题标题】:Handler in subdirectory of AWS Lambda function not runningAWS Lambda 函数子目录中的处理程序未运行
【发布时间】:2021-06-18 12:16:46
【问题描述】:

我在 Lambda 上遇到了一个非常不幸的错误:

Unable to import module 'lib/index': Error
at require (internal/module.js:20:19)

这很奇怪,因为肯定有一个名为 handler 的函数从 lib/index 导出...不确定整个子目录是否对其他人来说是个问题,所以我想问一下。

sam-template.yaml

AWSTemplateFormatVersion: '2010-09-09'
Transform: AWS::Serverless-2016-10-31
Description: Does something crazy
Resources:
  SomeFunction:
    Type: AWS::Serverless::Function
    Properties:
      Handler: lib/index.handler
      Role: arn:aws:iam::...:role/lambda-role
      Runtime: nodejs6.10
      Timeout: 10
      Events:
        Timer:
          Type: Schedule
          Properties:
            Schedule: rate(1 minute)

模块结构

|-- lib
|     `-- index.js
`-- src
      `-- index.js

我将它嵌套在这里是因为我在构建过程中使用以下代码转换 ES6,摘自package.json"build": "babel src -d lib"

buildspec.yaml

version: 0.1
phases:
    install:
        commands:
            - npm install
            - aws cloudformation package --template-file sam-template.yaml --s3-bucket some-bucket --output-template-file compiled-sam-template.yaml
    build:
        commands:
            - npm run build
    post_build:
        commands:
            - npm prune --production
artifacts:
    files:
        - 'node_modules/**/*'
        - 'lib/**/*'
        - 'compiled-template.yaml'

【问题讨论】:

    标签: node.js amazon-web-services aws-lambda


    【解决方案1】:

    aws cloudformation package 命令正在运送构建的资产,该资产在所示代码的install 阶段运行。将其移至 post_build 将确保它捕获所需的所有内容,包括相关的 lib/index

    post_build:
      commands:
        - npm prune --production
        - aws cloudformation package ...
    

    【讨论】:

      【解决方案2】:

      您正在尝试导入lib/index,它将尝试查找名为lib 的包,就像您执行npm install --save lib 一样,但您很可能尝试导入与您自己的项目相关的文件并且您没有提供它导入中的相对路径。

      'lib/index' 更改为 './lib/index' - 或 '../lib/index' 等 - 取决于它在哪里,看看是否有帮助。

      顺便说一句,如果您尝试导入文件 lib/index.js 而不是目录 lib/import/,那么您可以使用较短的 ./lib 路径,如下所示:

      const lib = require('./lib');
      

      当然,你连一行代码都没有显示,所以我只能猜测你在做什么。

      【讨论】:

      • 感谢您的回复!不幸的是,我尝试了以下两种Handler 值均无济于事:Handler: lib/index.handlerHandler: './lib/index.handler
      【解决方案3】:

      对处理程序的引用必须与要执行的 lambda 相关;

      例如: 如果文件 lambda 放在路径中:

      x-lambda/yyy/lambda.py
      

      处理程序必须是:

      ..yyy/lambda.lambda_handler
      

      假设在 lambda.py 中存在函数:lambda_handler()

      【讨论】:

      • 为什么在yyy 之前需要..
      • 因为你需要对脚本做相对引用
      猜你喜欢
      • 2020-05-02
      • 2020-02-25
      • 1970-01-01
      • 1970-01-01
      • 2020-01-04
      • 1970-01-01
      • 2016-09-04
      • 1970-01-01
      • 2019-01-27
      相关资源
      最近更新 更多