Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Situation Awareness
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive

Developing an Event Function

Updated on 2023-12-29 GMT+08:00

Function Syntax

NOTE:

You are advised to use Node.js 12.13.

  • Node.js 6.10

    Use the following syntax when creating a handler function in Node.js 6.10:

    export.handler = function(event, context, callback)

    • handler: name of the function that FunctionGraph invokes to execute your code. The name must be consistent with that you define when creating a function.
    • event: event parameter defined for the function. The parameter is in JSON format.
    • context: runtime information provided for executing the function. For details, see SDK APIs.
    • callback: used to return the defined err and message information to the frontend. The general syntax is callback(err, message). You can define the error or message content, for example, a character string.
    • Function handler: index.handler.

      The function handler is in the format of [File name].[Function name]. For example, if you set the handler to index.handler in your function, FunctionGraph will load the handler function defined in the index.js file.

  • Node.js 8.10, Node.js 10.16, Node.js 12.13, and Node.js 14.18

    Node.js 8.10, Node.js 10.16, Node.js 12.13, and Node.js 14.18 are compatible with the APIs of Node.js 6.10, and supports an async handler.

    exports.handler = async (event, context, callback [optional]) => { return data;}

    Responses are output through return.

Node.js Initializer

FunctionGraph supports the following Node.js runtimes:

  • Node.js6.10 (runtime = Node.js6)
  • Node.js8.10 (runtime = Node.js8)
  • Nodejs10.16(runtime = Node.js10)
  • Nodejs12.13(runtime = Node.js12)
  • Node.js16.17(runtime = Node.js16)
  • Node.js18.15(runtime = Node.js18)

Initializer syntax:

[File name].[Initializer name]

For example, if the initializer is named index.initializer, FunctionGraph loads the initializer function defined in the index.js file.

To use Node.js to build initialization logic, define a Node.js function as the initializer. The following is a simple initializer:

exports.initializer = function(context, callback) {
    callback(null, '');
    };
  • Function Name

    The function name exports.initializer must be the initializer function name specified for a function.

    For example, if the initializer is named index.initializer, FunctionGraph loads the initializer function defined in the index.js file.

  • context

    The context parameter contains the runtime information about a function. For example, request ID, temporary AK, and function metadata.

  • callback

    The callback parameter is used to return the invocation result. The signature of this parameter is function(err, data), which is the same as that of the common callback parameter used in Node.js. If the value of err is not null, the function will return HandledInitializationError. The value of data is invalid because no value will be returned for function initialization. You can set the data parameter to null by referring to the previous example.

SDK APIs

Table 1 describes the context methods provided by FunctionGraph.

Table 1 Context methods

Method

Description

getRequestID()

Obtains a request ID.

getRemainingTimeInMilliSeconds ()

Obtains the remaining running time of a function.

getAccessKey()

Obtains the AK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

NOTE:

FunctionGraph has stopped maintaining the getAccessKey API in the Runtime SDK. You cannot use this API to obtain a temporary AK.

getSecretKey()

Obtains the SK (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

NOTE:

FunctionGraph has stopped maintaining the getSecretKey API in the Runtime SDK. You cannot use this API to obtain a temporary SK.

getSecurityAccessKey()

Obtains the SecurityAccessKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getSecuritySecretKey()

Obtains the SecuritySecretKey (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getSecurityToken()

Obtains the SecurityToken (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getUserData(string key)

Uses keys to obtain the values passed by environment variables.

getFunctionName()

Obtains the name of a function.

getRunningTimeInSeconds ()

Obtains the timeout of a function.

getVersion()

Obtains the version of a function.

getMemorySize()

Obtains the allocated memory.

getCPUNumber()

CPU usage of a function.

getPackage()

Obtains a function group, that is, an app.

getToken()

Obtains the token (valid for 24 hours) with an agency. If you use this method, you need to configure an agency for the function.

getLogger()

Obtains the logger method provided by the context and returns a log output class. Logs are output in the format of Time-Request ID-Content by using the info method.

For example, use the info method to output logs:

logg = context.getLogger()

logg.info("hello")

getAlias

Obtains function alias.

WARNING:

Results returned by using the getToken(), getAccessKey(), and getSecretKey() methods contain sensitive information. Exercise caution when using these methods.

Execution Result

The execution result consists of the function output, summary, and log output.

Table 2 Description of the execution result

Parameter

Successful Execution

Failed Execution

Function Output

The defined function output information is returned.

A JSON file that contains errorMessage and errorType is returned. The format is as follows:

{
    "errorMessage": "", 
    "errorType":"", 
}

errorMessage: Error message returned by the runtime.

errorType: Error type.

Summary

Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed.

Request ID, Memory Configured, Execution Duration, Memory Used, and Billed Duration are displayed.

Log Output

Function logs are printed. A maximum of 4 KB logs can be displayed.

Error information is printed. A maximum of 4 KB logs can be displayed.

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback