All Products
Search
Document Center

Node.js handler

Last Updated: Dec 25, 2018

To use Node.js in Function Compute, you must define a Node.js function as a handler. Current Node.js runtime environments support either common handlers or handlers with an HTTP trigger. With the HTTP trigger, HTTP requests can be processed more efficiently. Except for the handlers with an HTTP trigger, all other Node.js-compiled function handlers are the same. For more information about Node.js runtime environments, see Node.js runtime environments.

Contents

This topic describes common handlers and handlers with an HTTP trigger.

Common handlers

A function is defined as follows:

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

Function name

exports.handler must match the “handler” field provided when a function is created. For example, if the handler is specified as index.handler, Function Compute obtains the handler function defined in the index.js file.

Parameter event

  • The event parameter is defined when you call a function. This parameter is of Buffer type and is an input parameter of the function.

  • This parameter is not defined by the function. When passed to the function, event is of the Buffer type. You can convert this parameter as needed. For example, if a JSON string is passed in, you can convert the parameter to an object. Example of Passed-in event:

    1. {
    2. "key": "value"
    3. }

    Function code:

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

    The value parameter is returned.

Parameter context

  • The context parameter contains information generated when a function is executed, such as the request ID and temporary security token. You can use the generated information when coding. This parameter is of the object type.

  • The context parameter can be defined as follows:

  1. {
  2. 'requestId': 'b1c5100f-819d-c421-3a5e-7782a27d8a33',
  3. 'credentials': {
  4. 'accessKeyId': 'STS.access_key_id',
  5. 'accessKeySecret': 'access_key_secret',
  6. 'securityToken': 'security_token',
  7. },
  8. 'function': {
  9. 'name': 'my-func',
  10. 'handler': 'index.handler',
  11. 'memory': 128,
  12. 'timeout': 10,
  13. },
  14. 'service': {
  15. 'name': 'my-service',
  16. 'logProject': 'my-log-project',
  17. 'logStore': 'my-log-store',
  18. 'qualifier': 'qualifier',
  19. 'versionId':'1',
  20. },
  21. 'region': 'cn-shanghai',
  22. 'accountId': '123456'
  23. }

In the preceding functions, key parameters include:

  • requestId: Indicates the unique ID of this call. Note down this parameter for easier troubleshooting if an exception occurs.
  • function: Indicates the basic information about this function, including the function name, handler, function memory, and timeout period.
  • credentials: Indicates a set of temporary security credentials that Function Compute obtains from assuming your service role. These credentials expire 6 hours after they are generated. You can use this parameter to access certain services, such as OSS. This prevents you from permanently writing your AccessKey credentials in the function code.
  • service: Specifies the details of the service that the current function serves. For example, this parameter may include the service name, and the log project and Logstore in Log Service, qualifier and versionId which indicate the service version.
  • region: Indicates the region to which this function applies, such as cn-shanghai.
  • accountId: Indicates the ID of your Alibaba Cloud account.

In the following code, STS is used to send a file to OSS.

  1. var OSSClient = require('ali-oss').Wrapper;
  2. exports.handler = function (event, context, callback) {
  3. console.log(event.toString());
  4. var ossClient = new OSSClient({
  5. accessKeyId: context.credentials.accessKeyId,
  6. accessKeySecret: context.credentials.accessKeySecret,
  7. stsToken: context.credentials.securityToken,
  8. region: 'oss-cn-shanghai',
  9. bucket: 'my-bucket',
  10. });
  11. ossClient.put('my-object', new Buffer('hello, fc')).then(function (res) {
  12. callback(null, 'put object');
  13. }).catch(function (err) {
  14. callback(err);
  15. });
  16. };

Note: You must issue a temporary security token so that STS can be used to access OSS.

Parameter callback

  • The callback parameter is used to return the result of the function that is called. The parameter signature is function(err, data). Similar to most of the callbacks of Node.js functions, the first parameter of callback is error and the second parameter is data. If the err parameter is not empty when a callback is called, HandledInvocationError is returned. Otherwise, the value of data is returned. If data is of Buffer type, the result is returned directly. If data is of object type, the result is returned after being converted. If data is of other types, the result is converted into a string and then returned.

Handlers with an HTTP trigger

Note: Handlers with an HTTP trigger are different from common handlers.

  1. function(request, response, context)

In the preceding function, the context parameter is the same as context of common handlers.

Parameter request

  • headers: This parameter is of map type and is used to store key-value pairs from the HTTP client.
  • path: This parameter is of string type and specifies the URL of the HTTP client.
  • queries: This parameter is of map type and is used to store the key-value pairs of the query requests from the URL of the HTTP client. The parameter value can be a string or an array.
  • method: This parameter is of string type. The HTTP method is used.
  • clientIP: This parameter is of string type and specifies the IP address of the client.
  • url: This parameter is of string type and specifies the URL of the request.

Obtaining the HTTP body: The request parameter in handlers with an HTTP trigger is compatible with HTTP requests. The body field is not provided. You can use an HTTP request to obtain the HTTP body.

  1. // For more information, see the following example.
  2. var getRawBody = require('raw-body')
  3. getRawBody(request, function(err, data){
  4. var body = data
  5. })

Note: If a key of the headers parameter contains the following fields, this key is ignored. This is because Function Compute provides the following fields by default. User-defined fields are not supported. Keys that start with x-fc- are also ignored.

  • accept-encoding
  • connection
  • keep-alive
  • proxy-authorization
  • te
  • trailer
  • transfer-encoding

Methods of obtaining responses

  • response.setStatusCode(statusCode): Sets the status code.
    • param statusCode: (required, type integer)
  • response.setHeader(headerKey, headerValue): Sets the header.
    • paramheaderKey: (required, type string)
    • paramheaderValue: (required, type string)
  • response.deleteHeader(headerKey): Deletes the header.
    • paramheaderKey: (required, type string)
  • response.send(body): Sends the body.
    • parambody: (required, typeBuffer or a string or a stream.Readable )

Note: If a key of the headers parameter contains the following fields, this key is ignored. This is because Function Compute provides the following fields by default. User-defined fields are not supported. Keys that start with x-fc- are also ignored.

  • connection
  • content-length
  • content-encoding
  • date
  • keep-alive
  • proxy-authenticate
  • server
  • trailer
  • transfer-encoding
  • upgrade

Limits

Limits on requests

If a request meets the following restrictions, a 400 status code and an InvalidArgument error code are displayed.

  • Size of headers: The size of all keys and values of the headers parameter cannot exceed 4 KB.
  • Size of path: The size of path equals the size of all query parameters, and it cannot exceed 4 KB.
  • Size of body: The size of the HTTP request body cannot exceed 6 MB.

Limits on responses

If a response meets the following restrictions, a 502 status code and a BadResponse error code are displayed.

  • Size of headers: The size of all keys and values of the headers parameter cannot exceed 4 KB.
  • Size of body: The size of the HTTP response body cannot exceed 6 MB.