文档首页/ 函数工作流 FunctionGraph/ 开发指南/ Node.js/ 使用华为云SDK开发Node.js函数示例
更新时间:2025-08-05 GMT+08:00
分享

使用华为云SDK开发Node.js函数示例

华为云API Explorer工具提供各云服务的API参考文档及配套SDK代码示例。

本章节指导您使用华为云SDK,在函数工作流控制台开发Node.js函数。

步骤一:创建Node.js函数

  1. 登录函数工作流控制台,右上角单击“创建函数”
  2. 创建一个空白的Node.js事件函数,建议选择较新的运行时版本,单击“立即创建”进入函数详情页。
  3. “代码”页签,下拉至“代码依赖包”模块,单击“添加依赖包”
  4. 图1所示,“依赖包源”选择“私有依赖包”,单击“创建依赖包”进入依赖包创建界面。
    图1 选择依赖包

  5. 请参考华为云Node.js SDK创建函数依赖包为函数创建所需的Node.js依赖包。

    请注意,创建Node.js依赖包时需选择与Node.js函数相同的运行时版本。

  6. 完成依赖包创建后,回到4添加已创建的依赖包。

步骤二:通过APIE获取SDK代码示例

  1. 打开API Explorer,如图2所示选择所需的接口,单击“代码示例”页签,选择“Node.js”语言。

    图2 APIE代码示例

    1. 此处以“获取函数列表”为例,选择接口。
    2. 填写接口所需的参数,参数描述可参考API参考手册中的相应章节,本例可参考获取函数列表API
    3. 复制APIE生成的代码,粘贴在步骤一:创建Node.js函数函数的代码编辑框中。

  2. 示例代码中的AK/SK信息建议配置在函数的环境变量中,并在代码中使用context.getUserData(string key)方法获取。

    改写后的代码内容如下:

    const core = require('@huaweicloud/huaweicloud-sdk-core');
    const functiongraph = require("@huaweicloud/huaweicloud-sdk-functiongraph/v2/public-api");
    exports.handler = async (event, context) => {
        const ak = context.getUserData("AK");
        const sk = context.getUserData("SK");
        const endpoint = "https://functiongraph.cn-north-4.myhuaweicloud.com";
        const project_id = "project_id";
        const credentials = new core.BasicCredentials()
            .withAk(ak)
            .withSk(sk)
            .withProjectId(project_id)
        const client = functiongraph.FunctionGraphClient.newBuilder()
            .withCredential(credentials)
            .withEndpoint(endpoint)
            .build();
        const request = new functiongraph.ListFunctionsRequest();
        request.marker = "marker";
        request.maxitems = "maxitems";
        request.packageName = "package_name";
        request.funcName = "func_name";
        const result = client.listFunctions(request);
        result.then(result => {
            console.log("JSON.stringify(result)::" + JSON.stringify(result));
        }).catch(ex => {
            console.log("exception:" + JSON.stringify(ex));
        });
        const output =
        {
            'statusCode': 200,
            'headers':
            {
                'Content-Type': 'application/json'
            },
            'isBase64Encoded': false,
            'body': JSON.stringify(event),
        }
        return output;
    }

  3. (可选)如需使用更安全的鉴权方式,可将以下代码内容替换:

    const ak = context.getUserData("AK");
    const sk = context.getUserData("SK");
    const credentials = new core.BasicCredentials()
        .withAk(ak)
        .withSk(sk)
        .withProjectId(project_id)

    替换为:

    const ak = context.getSecurityAccessKey();
    const sk = context.getSecuritySecretKey();
    const st = context.getSecurityToken();
    const credentials = new core.BasicCredentials()
        .withAk(ak)
        .withSk(sk)
        .withProjectId(project_id)
        .with_security_token(st)

相关文档