node.js - 如何从 AWS Lambda (Node.js) 中的处理程序调用 module.exports

标签 node.js aws-lambda

这就是 AWS 中所说的:

The module-name.export value in your function. For example, "index.handler" calls exports.handler in index.js.

它正确地调用了这个函数:

exports.handler = (username, password) => {
    ...
}

但是如果代码是这样的呢:

module.exports = (username, password) => {
    ...
}

如何调用它?我没有尝试像 module.exportsmodule.handler 等一样工作。

最佳答案

AWS Lambda 期望您的模块导出包含处理程序函数的对象。然后在您的 Lambda 配置中声明包含该模块的文件和处理函数的名称。

在 Node.js 中导出模块的方式是通过 module.exports 属性。 require 调用的返回值是文件评估结束时 module.exports 属性的内容。

exports 只是一个指向 module.exports 的局部变量。您应该避免使用 exports,而是使用 module.exports,因为其他一些代码可能会覆盖 module.exports,从而导致意外行为.

在您的第一个代码示例中,该模块正确导出了一个具有单个函数 handler 的对象。然而,在第二个代码示例中,您的代码导出了一个函数。由于这与 AWS Lambda 的 API 不匹配,因此不起作用。

考虑以下两个文件,export_object.js 和 export_function.js:

// export_object.js

function internal_foo () {
    return 1;
}

module.exports.foo = internal_foo;

// export_function.js

function internal_foo () {
    return 1;
}

module.exports = internal_foo;

当我们运行 require('export_object.js') 时,我们得到一个只有一个函数的对象:

> const exp = require('./export_object.js')
undefined
> exp
{ foo: [Function: internal_foo] }

将其与我们运行 require('export_function.js') 时得到的结果进行比较,我们只得到一个函数:

> const exp = require('./export_funntion.js')
undefined
> exp
[Function: internal_foo]

当您配置 AWS Lambda 以运行名为 handler 的函数时,该函数导出到文件 index.js 中定义的模块中,这里是 Amazon 的近似值当函数被调用时:

const handler_module = require('index.js');
return handler_module.handler(event, context, callback);

重要的部分是调用模块中定义的处理函数。

关于node.js - 如何从 AWS Lambda (Node.js) 中的处理程序调用 module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52639302/

相关文章:

python-3.x - 从 lambda 函数调用 cloudformation

python - Zappa 部署错误 : GET request yields 502 response code

javascript - 如何为我的聊天机器人制作自定义回复卡

javascript - 如何在 Node 中读取本地 Markdown 文件?

android - 如何使用 socket.io 模块从 android 向 nodejs 服务器发送数据?

windows - NPM Windows 路径问题

amazon-web-services - 使用 Winston 日志记录的 AWS Lambda 丢失请求 ID

node.js - 在 Mocha 中测试异步抛出

Node.js - npm test <package> 默默地成功,没有任何输出?

amazon-web-services - 每个 Lambda 的 AWS Lambda 不同的 IP 地址