简体   繁体   English

无法在AWS Lambda中使用NPM包,require()已损坏

[英]Unable to use NPM package inside AWS Lambda, require() broken

I have created a very basic NPM package with only two files 我创建了一个非常基本的NPM包,只有两个文件

index.js: index.js:

  module.exports = {
      errors: {
        HttpError: require('./src/errors').HttpError,
        test: 'value'
      }
    }

src/errors.js: SRC / errors.js:

class HttpError extends Error {
  constructor (message, code) {
    super(message)
    this.statusCode = code

    if (Error.captureStackTrace) {
      Error.captureStackTrace(this, HttpError)
    }
  }
}

exports.HttpError = HttpError

When I install this package I can use my error class without any problems. 当我安装这个包时,我可以使用我的错误类没有任何问题。 However, when I create a deployment package with Serverless and try to run the code as part of an AWS Lambda, the lambda does not seem to be able to resolve the HttpError class. 但是,当我使用Serverless创建部署包并尝试将代码作为AWS Lambda的一部分运行时,lambda似乎无法解析HttpError类。

In my lambda function running on AWS, when I have required the package as a const and log it out the log looks like this: 在我在AWS上运行的lambda函数中,当我需要将包作为const并将其注销时,日志如下所示:

{"errors":{"test":"value"}}

whereas locally it looks like: 而在本地它看起来像:

{ errors:
   { HttpError: [Function: HttpError],
     test: 'value' } }

I have downloaded the deployment package from AWS and can confirm that it looks exactly like the local version. 我从AWS下载了部署包,可以确认它看起来与本地版本完全一样。 I can't find anything in the lambda docs that imply that I can't use require for javascript modules. 我在lambda文档中找不到任何暗示我不能对JavaScript模块使用require的东西。 What am I doing wrong? 我究竟做错了什么?

I found the error and it was entirely of my own doing, by making two separate mistakes at the same time. 我发现了错误,这完全是我自己做的,同时犯了两个不同的错误。

I was checking if my package-name.errors.HttpError was an instanceof an identical HttpError class that I had defined in the code that was installing the package, which of course it was not. 我正在检查我的package-name.errors.HttpError是否是我在安装包的代码中定义的相同HttpError类的实例,当然它不是。 This lead me to log out the result of the require(), however, I was using JSON.stringify() to do this which of course will omit functions. 这导致我注销require()的结果,但是,我使用JSON.stringify()来做这个当然会省略函数。 Thus I believed that somehow my require() inside the package was not being resolved correctly. 因此我相信我的包内的require()不能正确解析。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM