When you use Node.js for programming in Function Compute, you must define a Node.js function as the handler function. This topic describes the structure and features of Node.js event functions.

Definition

The following code defines a simple handler function:

exports.handler = function(event, context, callback) {
  callback(null, 'hello world');
};       
The function definition contains the following parts:

Function name

In this example, handler must correspond to the handler field that you specified when you created the event function. For example, if you set the handler field to index.handler when you create the event function, Function Compute loads the handler function defined in the index.js file.

event parameter

  • The event parameter indicates the data that is passed in when you call a function. The event parameter is of the buffer type and is an input parameter of the function.
  • When the event parameter is passed to the function, you can convert this parameter as needed. If a JSON string is passed in, you can convert it to an object.
    {
    "key": "value"
    }          

    For example, event is passed in and value is returned.

    exports.handler = function(event, context, callback) {
      var eventObj = JSON.parse(event.toString());
      callback(null, eventObj['key']);
    };          

context parameter

The context parameter contains the runtime information of a function, such as the request ID and the temporary AccessKey pair. You can use the runtime information in your code. This parameter is of the object type and can be defined as follows:

{
  'requestId': 'b1c5100f-819d-c421-3a5e-7782a27d8a33',
  'credentials': {
    'accessKeyId': 'STS.access_key_id',
    'accessKeySecret': 'access_key_secret',
    'securityToken': 'security_token',
  },
  'function': {
    'name': 'my-func',
    'handler': 'index.handler',
    'memory': 128,
    'timeout': 10,
    'initializer': 'index.initializer',
    'initializationTimeout': 10,
  },
  'service': {
     'name': 'my-service',
     'logProject': 'my-log-project',
     'logStore': 'my-log-store',
     'qualifier': 'qualifier',
     'versionId': '1'
  },
  'region': 'cn-shanghai',
  'accountId': '123456'
}
            

The following table lists the fields contained in the context parameter.

Field Description
requestId The unique ID of the call request. You can record the ID for troubleshooting if an error occurs.
function The basic information of the current function, such as the name, handler, memory, and timeout period of the function.
credentials The temporary AccessKey pair obtained by Function Compute from assuming your service role. The temporary AccessKey pair is valid for six hours. You can use credentials in your code to access the related service such as Object Storage Service (OSS). This allows you not to hardcode your AccessKey pair in the function code.

For more information about permissions, see User permissions.

service The information about the service to which the function belongs. This field contains the service name, the project and Logstore information of Log Service (SLS) to which the service is connected, and qualifier and version_id that indicate the service version information. The qualifier parameter indicates the service version or alias that is specified when the function is called. The version_id parameter indicates the version of the service that is called.
region The region to which the function applies, such as cn-shanghai.
accountId The ID of the Alibaba Cloud account that calls the function.

The following sample code shows how to upload a file to OSS by using a temporary AccessKey pair.

var OSSClient = require('ali-oss').Wrapper;

exports.handler = function (event, context, callback) {
    console.log(event.toString());

    var ossClient = new OSSClient({
        accessKeyId: context.credentials.accessKeyId,
        accessKeySecret: context.credentials.accessKeySecret,
        stsToken: context.credentials.securityToken,
        region: 'oss-cn-shanghai',
        bucket: 'my-bucket',
    });

    ossClient.put('my-object', new Buffer('hello, fc')).then(function (res) {
        callback(null, 'put object');
    }).catch(function (err) {
        callback(err);
    });
};
            
Notice When you use a temporary AccessKey pair to access OSS, you must add the securityToken parameter.

callback function

The callback function is defined by the system as an input parameter of a handler function. It is used to return the call result of a function, indicating the end of function execution. The signature of the callback function is function(err, data), which is similar to that of the callback function in Node.js. In the signature, the first parameter is error and the second parameter is data.

If the error parameter is not empty when the function is called, the function returns HandledInvocationError. If the error parameter is empty, the function returns the content of the data parameter.

  • If the data parameter is of the buffer type, the function directly returns the content of the data parameter.
  • If the data parameter is of the object type, the function converts the content of the data parameter to a JSON string and then returns the JSON string.
  • If the data parameter is of other types, the function converts the content of the data parameter to a string and then returns the string.