javascript 如何使用 NodeJS 在本地测试 AWS Lambda 处理程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/52019039/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test AWS Lambda handler locally using NodeJS?
提问by kroe761
I am following theseinstructions to create a basic web scraper that executes in Lambda. I have experience writing selenium code, but not with Node JS. I got the project running in Lambda, but when I tried editing the project locally in order to execute the selenium code I want, It doesn't work. Anything in the exports.handlerdoesn't get executed when I run node index.js. How would I execute this project locally? Thanks!
我正在按照这些说明创建一个在 Lambda 中执行的基本网络抓取工具。我有编写 selenium 代码的经验,但没有使用 Node JS。我让项目在 Lambda 中运行,但是当我尝试在本地编辑项目以执行我想要的 selenium 代码时,它不起作用。在任何exports.handler时候我运行没有得到执行node index.js。我将如何在本地执行这个项目?谢谢!
回答by NAVIN
You need to call your handler function from another file lets say testHandler.jsin order to run via NodeJs.
您需要从另一个文件中调用您的处理程序函数testHandler.js,以便通过 NodeJs 运行。
This will be done like this
这将像这样完成
//import your handler file or main file of Lambda
let handler = require('./handler');
//Call your exports function with required params
//In AWS lambda these are event, content, and callback
//event and content are JSON object and callback is a function
//In my example i'm using empty JSON
handler.handlerEvent( {}, //event
{}, //content
function(data,ss) { //callback function with two arguments
console.log(data);
});
Now you can use node testHandler.jsto test your handler function.
现在您可以使用node testHandler.js来测试您的处理程序函数。
EDIT: Sample Event and content dataas requested
编辑:按要求提供示例事件和内容数据
Event:
事件:
{
"resource": "/API/PATH",
"path": "/API/PATH",
"httpMethod": "POST",
"headers": {
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-GB,en-US;q=0.9,en;q=0.8",
"cache-control": "no-cache",
"CloudFront-Forwarded-Proto": "https",
"CloudFront-Is-Desktop-Viewer": "true",
"CloudFront-Is-Mobile-Viewer": "false",
"CloudFront-Is-SmartTV-Viewer": "false",
"CloudFront-Is-Tablet-Viewer": "false",
"CloudFront-Viewer-Country": "IN",
"content-type": "application/json",
"Host": "url.us-east-1.amazonaws.com",
"origin": "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop",
"User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"Via": "2.0 XXXXXXXXXXXXXX.cloudfront.net (CloudFront)",
"X-Amz-Cf-Id": "XXXXXXXXXX51YYoOl75RKjAWEhCyna-fuQqEBjSL96TMkFX4H0xaZQ==",
"X-Amzn-Trace-Id": "Root=1-XXX03c23-25XXXXXX948c8fba065caab5",
"x-api-key": "SECUREKEY",
"X-Forwarded-For": "XX.XX.XXX.XXX, XX.XXX.XX.XXX",
"X-Forwarded-Port": "443",
"X-Forwarded-Proto": "https"
},
"multiValueHeaders": {
"Accept": [ "*/*" ],
"Accept-Encoding": [ "gzip, deflate, br" ],
"Accept-Language": [ "en-GB,en-US;q=0.9,en;q=0.8" ],
"cache-control": [ "no-cache" ],
"CloudFront-Forwarded-Proto": [ "https" ],
"CloudFront-Is-Desktop-Viewer": [ "true" ],
"CloudFront-Is-Mobile-Viewer": [ "false" ],
"CloudFront-Is-SmartTV-Viewer": [ "false" ],
"CloudFront-Is-Tablet-Viewer": [ "false" ],
"CloudFront-Viewer-Country": [ "IN" ],
"content-type": [ "application/json" ],
"Host": [ "apiurl.us-east-1.amazonaws.com" ],
"origin": [ "chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop" ],
"User-Agent": [ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" ],
"Via": [ "2.0 XXXXXXXXXXXXXX.cloudfront.net (CloudFront)" ],
"X-Amz-Cf-Id": [ "XXXXXXXXXhCyna-fuQqEBjSL96TMkFX4H0xaZQ==" ],
"X-Amzn-Trace-Id": [ "Root=1-XXXXXXX67339948c8fba065caab5" ],
"x-api-key": [ "SECUREAPIKEYPROVIDEDBYAWS" ],
"X-Forwarded-For": [ "xx.xx.xx.xxx, xx.xxx.xx.xxx" ],
"X-Forwarded-Port": [ "443" ],
"X-Forwarded-Proto": [ "https" ]
},
"queryStringParameters": null,
"multiValueQueryStringParameters": null,
"pathParameters": null,
"stageVariables": null,
"requestContext": {
"resourceId": "xxxxx",
"resourcePath": "/api/endpoint",
"httpMethod": "POST",
"extendedRequestId": "xxXXxxXXw=",
"requestTime": "29/Nov/2018:19:21:07 +0000",
"path": "/env/api/endpoint",
"accountId": "XXXXXX",
"protocol": "HTTP/1.1",
"stage": "env",
"domainPrefix": "xxxxx",
"requestTimeEpoch": 1543519267874,
"requestId": "xxxxxxx-XXXX-xxxx-86a8-xxxxxa",
"identity": {
"cognitoIdentityPoolId": null,
"cognitoIdentityId": null,
"apiKey": "SECUREAPIKEYPROVIDEDBYAWS",
"cognitoAuthenticationType": null,
"userArn": null,
"apiKeyId": "xxXXXXxxxxxx",
"userAgent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36",
"accountId": null,
"caller": null,
"sourceIp": "xx.xxx.xxx.xxx",
"accessKey": null,
"cognitoAuthenticationProvider": null,
"user": null
},
"domainName": "url.us-east-1.amazonaws.com",
"apiId": "xxxxx"
},
"body": "{\n \"city\": \"Test 1 City\",\n \"state\": \"NY\",\n \"zipCode\": \"11549\"\n}",
"isBase64Encoded": false
}
Content:
内容:
{
"callbackWaitsForEmptyEventLoop": true,
"logGroupName": "/aws/lambda/lambda-name",
"logStreamName": "2018/11/29/[$LATEST]xxxxxxxxxxxb",
"functionName": "lambda-name",
"memoryLimitInMB": "1024",
"functionVersion": "$LATEST",
"invokeid": "xxxxx-xxx-11e8-xxx-xxxxxxxf9",
"awsRequestId": "xxxxxx-xxxxx-11e8-xxxx-xxxxxxxxx",
"invokedFunctionArn": "arn:aws:lambda:us-east-1:xxxxxxxx:function:lambda-name"
}
回答by jmk
This is what I did:
这就是我所做的:
index.js
索引.js
exports.handler = async (event) => {
console.log('hello world');
const response = {
statusCode: 200,
body: JSON.stringify('Hello from Lambda!')
};
return response;
};
package.json
包.json
"scripts": {
"locally": "node -e \"console.log(require('./index').handler({}));\""
}
Shell
壳
npm run locally
Output
输出
> node -e "console.log(require('./index').handler({}));"
hello world
Promise { { statusCode: 200, body: '"Hello from Lambda!"' } }
回答by John
In your index.js, just defined and exported a handler function, but no one calls it. In the Lambda environment, some AWS code will call this handler with message. In your local environment, you have to call your handler by yourself.
在您的 中index.js,刚刚定义并导出了一个处理程序函数,但没有人调用它。在 Lambda 环境中,一些 AWS 代码将使用消息调用此处理程序。在您的本地环境中,您必须自己调用处理程序。
You could also have a look of this doc, it is a way to "simulate" Lambda in local environment.
你也可以看看这个 doc,它是一种在本地环境中“模拟” Lambda 的方法。
回答by Schof
You can check out lambda-local. It's a little fancier than the accepted answer above. For example, it supports passing environment variables and using JSON files for your payloads.
您可以查看lambda-local。它比上面接受的答案更花哨。例如,它支持传递环境变量并为您的有效负载使用 JSON 文件。
回答by Schof
If you want just to execute it locally you can use the official sam clitool
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-invoke.html
如果您只想在本地执行它,您可以使用官方sam cli工具
https://docs.aws.amazon.com/serverless-application-model/latest/developerguide/sam-cli-command-reference-sam-local-invoke。 html
If you use VSCode you can also check out this extension:
如果您使用 VSCode,您还可以查看此扩展:
https://marketplace.visualstudio.com/items?itemName=bogdan-onu.invoke
https://marketplace.visualstudio.com/items?itemName=bogdan-onu.invoke
回答by Ilarion Halushka
Official Docs for Step-Through Debugging Node.js Functions Locally:
在本地逐步调试 Node.js 函数的官方文档:


