node.js - 如何从 AWS Lambda (Node.js) 中的处理程序调用 module.exports
问题描述
这就是 AWS 中所说的:
函数中的 module-name.export 值。例如,“index.handler”调用index.js 中的exports.handler。
它正确地调用了这个函数:
exports.handler = (username, password) => {
...
}
但是如果代码是这样的:
module.exports = (username, password) => {
...
}
我怎么称呼它?我没有尝试过像module.exports
,module.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);
重要的部分是对模块中定义的处理函数的调用。
推荐阅读
- linux - 使用 SSH 从 jenkins 运行 SSH 脚本命令
- linux - 如何在文件及其上方和下方的行中排除匹配的模式?
- react-native - 添加新的 RN 包后,我得到“SDK 构建工具版本对于项目来说太低”
- active-directory - 从同步中排除谷歌用户 - 谷歌 GCDS
- twig - Twig 模板添加 JSON-LD 副本
- assembly - 使用无 PWM 和模拟的组装更改 Atmel AVR 中的 LED 亮度
- r - 使用数据分层的 wilcoxon 检验
- fortran - 如何使用 fortran 为 dgemm_batch 创建一个指针数组?
- java - 使用 Spring Security + Spring Session 将身份验证设置为 true
- c# - Serilog 的 sublogger 过滤器无法正常工作