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

Ama*_*day 2 node.js aws-lambda

这就是AWS中的说法:

函数中的module-name.export值。例如,“ index.handler”在index.js中调用exports.handler。

并正确调用此函数:

exports.handler = (username, password) => {
    ...
}
Run Code Online (Sandbox Code Playgroud)

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

module.exports = (username, password) => {
    ...
}
Run Code Online (Sandbox Code Playgroud)

我怎么称呼它?没什么我想喜欢的作品module.exportsmodule.handler等等。

小智 5

AWS Lambda希望您的模块导出包含处理程序功能的对象。然后,在Lambda配置中,声明包含模块的文件以及处理程序函数的名称。

通过module.exports属性在Node.js中导出模块的方式。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;
Run Code Online (Sandbox Code Playgroud)

// export_function.js

function internal_foo () {
    return 1;
}

module.exports = internal_foo;
Run Code Online (Sandbox Code Playgroud)

运行时,require('export_object.js')我们将获得一个具有单个功能的对象:

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

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

> const exp = require('./export_funntion.js')
undefined
> exp
[Function: internal_foo]
Run Code Online (Sandbox Code Playgroud)

当您配置AWS Lambda运行名为的功能时handler,该功能会在文件中定义的模块中导出index.js,这是调用功能时Amazon所做的近似:

const handler_module = require('index.js);
return handler_module.handler(event, context, callback);
Run Code Online (Sandbox Code Playgroud)

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