How to debug aws lambda functions written in node js

后端 未结 9 3121
孤城傲影
孤城傲影 2021-02-20 13:34

We have been developing AWS Lambda functions in Node JS for a few months. Can we debug, i.e. step through the Node JS code as we can with .Net C# code in Visual Studio?

9条回答
  •  南旧
    南旧 (楼主)
    2021-02-20 14:10

    I would like to share what I have found as I had had some hard time trying to find it out. The solution is based on what I found on article "Debugging AWS Lambda Functions Locally using VS Code and lambda-local"(https://www.codeproject.com/Articles/1163890/Debugging-AWS-Lambda-functions-locally-using-VS-Co) with some modification in order to work in our Windows based environment.

    Here is the summary:

    1) To use Visual Studio Code to lunch a debug session. Am example of launch.json for debugging 'llDebugDetail.js' is as below:

    {
        "version": "0.2.0",
        "configurations": [
            {
                "type": "node",
                "request": "launch",
                "name": "Launch Program",
                "program": "${workspaceRoot}/test/llDebugDetail.js",
                "cwd": "${workspaceRoot}"
            }
        ]
    }
    

    2) To use the lambda-local framework to call (execute) the lambda function. The lambda-local framework has to be installed locally, otherwise the VSC debugger won't find it. Our lambda function is invoked by calling the following URL: https://xxx.execute-api.ap-southeast-2.amazonaws.com/resourceName/{id}/detail. The {id} is a GUID parameter for selecting a product item and returning its details.

    Here is the 'llDebugDetail.js' code for calling the 'getDetail' function for returning product details with the GUID as its id in the URL. The function is within the 'getDetail.js' file.

    const lambdaLocal = require('lambda-local');
    var path = require("path");
    const myPath = path.join(__dirname, '../getDetail.js');
    const testEvent = {
        "resource": "resourceName/12da3f7d-7ce2-433f-8659-5d7cd0d74d9a/detail",
        "pathParameters": {"id": "12da3f7d-7ce2-433f-8659-5d7cd0d74d9a"}
    }
    
    var lambdaFunc = require(myPath);
    
    lambdaLocal.execute({
        event: testEvent,
        lambdaFunc: lambdaFunc, 
        lambdaHandler: "getDetail"
    }).then(function(done) {
        console.log(done);
    }).catch(function(err) {
        console.log(err);
    });
    

    With the above done, you can now set break points anywhere within your code, e.g. inside getDetail.js, launch the program and the step through the code from the break points within getDetail.js.

提交回复
热议问题