This topic describes the structural features and examples of Node.js event request handlers.

Event Handler Signature

A simple Event Handler signature is defined as follows.

exports.handler = function(event, context, callback) {
  callback(null, 'hello world');
};

The example of Event Handler is parsed as follows:

  • handler: the name of the method. Corresponding to the request handler (function entry) configured in the Function Compute console. For example, if the request handler (function entry) configured for the FC function is index.handler, the Function Compute will load the handler function defined in the index.js and execute it from the handler function.
  • event: the parameter that you passed in when you called the function. In the Node.js runtime environment, the value type is Buffer.
  • context: Provides the runtime context information for your FC function call at the time of the call.
  • callback: a callback function that identifies the end of function execution and returns the result. The signature is a function(error, data). If the error is null, it is returned normally. The returned content is data. Otherwise, an exception is returned and the error message is error.
    Note Depending on the type of the data, the Function Compute converts the returned results accordingly.
    • Buffer type: does not convert and is returned as is.
    • Object type: returned after conversion to JSON format.
    • Other types: returned after conversion to a string.

You can also use asynchronous function signatures, as shown in the following example.

exports.handler = async function(event, context, callback) {
  callback(null, 'hello world');
};

Example 1: Parse JSON-formatted parameters

Sample code

When you specify a JSON-formatted parameter, the Function Compute passes through the parameter content and requires you to parse it in the code. The following is a code example for parsing JSON-formatted events.

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

Prerequisites

Create a function

Procedure

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where your Kubernetes cluster is deployed.
  4. On the Functions page, click the name of the function that you want to manage.
  5. On the Function Details page, click the Function Code tab, enter the preceding sample code in the code editor, and then click Save and Deploy.
    Note The request handler for the function in the preceding sample code is the handler method in the index.js. If the request handler (function entry) configuration of your function is different, find the corresponding file and method to update it.
  6. On the Function Code tab, click the down icon next to Test Function, select Configure Test Parameters from the drop-down list, enter the following test parameters, and then click OK.
    {
      "key": "value"
    }
  7. Click Test Function.
    After the function is successfully executed, view the returned result. You can see that the returned result is value.

Example 2: Securely read and write OSS resources by using a temporary key

Sample code

You can use the temporary key provided by the Function Compute to access the OSS, as shown in the following code example.

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

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-shenzhen',
        bucket: 'my-bucket',
    });

    ossClient.put('myObj', Buffer.from('hello, fc', "utf-8")).then(function (res) {
        callback(null, 'put object');
    }).catch(function (err) {
        callback(err);
    });
};
The sample code is parsed as follows:
  • context.credentials: indicates that the temporary key is obtained from the context parameters to avoid hard-coding sensitive information such as passwords in the code.
  • myObj: the name of the OSS object.
  • Buffer.from('hello, fc', "utf-8"): the content of the uploaded object.
  • callback(null, 'put object'): The upload is successful and the put object is returned.
  • callback(err): The err is returned when the upload fails.

Prerequisites

Procedure

  1. Log on to the Function Compute console.
  2. In the left-side navigation pane, click Services and Functions.
  3. In the top navigation bar, select the region where your Kubernetes cluster is deployed.
  4. On the Functions page, click the name of the function that you want to manage.
  5. On the Function Details page, click the Function Code tab, enter the preceding sample code in the code editor, and then click Save and Deploy.
    Note The request handler for the function in the preceding sample code is the handler method in the index.js. If the request handler (function entry) configuration of your function is different, find the corresponding file and method to update it.
  6. Click Test Function.
    After the function is successfully executed, view the returned result. You can see that the returned result is put object.

Example 3: Call an external command

Your Node.js program can also create fork processes and call external commands. For example, you can use the child_process module to call ls -l commands in Linux to output a list of files in the current directory. Sample code:

'use strict';

var exec = require('child_process').exec;
exports.handler = (event, context, callback) => {
  console.log('start to execute a command');
  exec("ls -l", function(error, stdout, stderr){
    callback(null, stdout);
});
}