Node.js和Python函数

更新时间:
复制为 MD 格式

Node.jsPython类型函数的调试方式基本一致。本文以Node.js为例,介绍如何通过VSCode调试本地事件函数。

重要

本文介绍的内容后期将不再维护。如果您的函数计算资源是使用Funcraft管理的,建议您将资源迁移至Serverless Devs管理。

关于如何将函数计算的相关资源从Funcraft迁移到Serverless Devs进行管理的详细操作,请参见Funcraft迁移到Serverless Devs

由此带来的不便,敬请谅解!

关于Serverless Devs的详细信息,请参见什么是Serverless Devs

操作步骤

本文以函数名demo、调试端口3000为例。

  1. 执行以下命令调试函数。

    fun local invoke -d 3000 --config VSCode demo

    预期输出。

    using template: template.yml
    skip pulling image aliyunfc/runtime-nodejs8:1.9.6...
    you can paste these config to .vscode/launch.json, and then attach to your running function
    ///////////////// config begin /////////////////
    {
        "version": "0.2.0",
        "configurations": [
            {
                "name": "fc/demo/demo",
                "type": "node",
                "request": "attach",
                "address": "localhost",
                "port": 3000,
                "localRoot": "C:\\Users\\XX\\Desktop\\target\\demo",
                "remoteRoot": "/code",
                "protocol": "inspector",
                "stopOnEntry": false
            }
        ]
    }
    ///////////////// config end /////////////////
    Debugger listening on ws://0.0.0.0:3000/b65c288b-bd6a-4791-849b-b03e0d******
    For help see https://nodejs.org/en/docs/inspector

    执行完以上命令后,程序将会被阻塞不会继续调试执行。您需按照以下操作连接IDE,只有成功连接IDE后,程序才会继续执行。

  2. 成功执行上一步骤后,配置VSCode。

    说明

    VSCode只需在第一次调试函数时配置。如果已经配置过,则无需再次配置。

    1. 选择run-icon > create a launch.json file,创建launch.json文件。

    2. 复制输出日志config beginconfig end之间的信息至launch.json中。如果您需要了解更多VSCode的详细信息,请参见VSCode

      {
          "version": "0.2.0",
          "configurations": [
              {
                  "name": "fc/localdemo/nodejs8",
                  "type": "node",
                  "request": "attach",
                  "address": "localhost",
                  "port": 3000,
                  "localRoot": "/Users/tan/code/fun/examples/local/nodejs8",
                  "remoteRoot": "/code",
                  "protocol": "inspector",
                  "stopOnEntry": false
              }
          ]
      }

      完成上面配置后,在Debug视图中您可以查看到配置的函数列表。在 VS Code 的 DEBUG 面板中,从配置下拉框中选择 fc/localdemo/nodejs8 调试配置,单击运行按钮启动调试。

  3. 使用VSCode调试Node.js函数。

    1. 单击VSCode编辑器侧边栏设置断点,示例代码如下。

      var counter = 0;
      exports.initializer = function(counter, callback) {
          counter += 1;
          callback(null, "");
      };
      exports.handler = function(event, context, callback) {
          var eventObj = JSON.parse(event.toString());
          console.log("event: " + event);
          console.log('context: ', JSON.stringify(context));
          counter += 2;
          callback(null, String(counter));
      };
    2. 然后单击IMagevscode2图标,即可开始调试。

操作视频

以下是函数本地单步调试的操作视频。