AWS Lambda 希望您的模块导出包含处理程序函数的对象。然后,您可以在 Lambda 配置中声明包含该模块的文件以及处理程序函数的名称。
Node.js 中导出模块的方式是通过module.exports
财产。 a的返回值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;
and
// 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);
重要的部分是调用模块中定义的处理函数。