首页 > 解决方案 > 如何从 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等这样的作品。

标签: node.jsaws-lambda

解决方案


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);

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


推荐阅读