这就是 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.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);
重要的部分是调用模块中定义的处理函数。
关于node.js - 如何从 AWS Lambda (Node.js) 中的处理程序调用 module.exports,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52639302/