How to debug aws lambda functions written in node js

后端 未结 9 3337
孤城傲影
孤城傲影 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 13:57

    Debugging lambda using breakpoints in VSCode:

    First, write test cases for your handler as follows: index.test.js

    'use strict';
    
    const handler = require('../index');
    
    const chai = require('chai');
    
    const { expect } = chai;
    
    describe('debug demo', () => {
      it('should return success', () => {
        let event = {data: "some data"}
        handler(event, '', function(err, res) {
          expect(res.statusCode, '200')
        });
      });
    });
    

    Now add the VSCode debugger configuration

    Step 1: Click on debugger icon on the left side

    Step 2: Click Add configurations

    and add the following configurations in launch.json file:

    {
        "version": "0.2.0",
        "configurations": [
    
          {
              "type": "node",
              "request": "launch",
              "name": "Mocha All",
              "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
              "args": [
                  "--timeout",
                  "999999",
                  "--colors",
                  "'${workspaceFolder}/lambda-codebase/**/test/*.test.js'"
              ],
              "console": "integratedTerminal",
              "internalConsoleOptions": "neverOpen"
          },
          {
              "type": "node",
              "request": "launch",
              "name": "Mocha Current File",
              "program": "${workspaceFolder}/node_modules/mocha/bin/_mocha",
              "args": [
                  "--timeout",
                  "999999",
                  "--colors",
                  "${file}"
              ],
              "console": "integratedTerminal",
              "internalConsoleOptions": "neverOpen"
          }
        ]
      }
    

    Step 3: Now add a breakpoint to code which you wants to debug as follows:

    Step 4: Now focus on the test file by clicking on the file:

    Step 5: Choose the option from the drop-down "Mocha All" to run the complete solution and "Mocha current file" to run only selected file

    Now click on the DEBUG Play button and enjoy the debugging!

自定义标题
段落格式
字体
字号
代码语言
提交回复
热议问题