edit-icon download-icon

Node.js runtime

Last Updated: Aug 07, 2018

Currently, Function Compute supports the Node.js 6.10 (runtime version 6) and Node.js 8.9.0 (runtime version 8).

Contents

This topic describes the following features of Node.js runtime environments:

Use the logging module

The data that the function outputs using console.log is collected to the Logstore that is specified when a service is created. For more information about function logs, see Function logs.

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

After the preceding commands are run, the following output is displayed:

  1. message:2017-07-05T05:13:35.920Z a72df088-f738-cee3-e0fe-323ad89118e5 [INFO] hello world

You can run the console.warn and console.error commands to package WARN and ERROR log entries, respectively.

You can change log levels using setLogLevel. The following log levels are listed in descending order of priority:

  • error: indicates that the corresponding handler is console.error.
  • warn: indicates that the corresponding handler is console.warn.
  • info: indicates that the corresponding handler is console.info.
  • verbose: indicates that the corresponding handler is console.log.
  • debug: indicates that the corresponding handler is console.debug.
  1. 'use strict';
  2. exports.handler = function(evt, ctx, cb) {
  3. console.setLogLevel("error");
  4. console.error("console error 1");
  5. console.info("console info 1");
  6. console.warn("console warn 1");
  7. console.log("console log 1");
  8. console.setLogLevel("warn");
  9. console.error("console error 2");
  10. console.info("console info 2");
  11. console.warn("console warn 2");
  12. console.log("console log 2");
  13. console.setLogLevel("info");
  14. cb(null, evt);
  15. };

After the preceding commands are run, the following output is displayed:

  1. message:2017-07-05T05:13:35.920Z a72df088-f738-cee3-e0fe-323ad89118e5 [ERROR] console error 1
  2. message:2017-07-05T05:13:35.920Z a72df088-f738-cee3-e0fe-323ad89118e5 [ERROR] console error 2
  3. message:2017-07-05T05:13:35.920Z a72df088-f738-cee3-e0fe-323ad89118e5 [WARN] console warn 2

Use built-in modules

In addition to the standard logging module, the Node.js runtime environments for Function Compute provide other modules that users can access. Currently, the modules detailed in the following table are available.

Module Description Related link
co Control flow https://github.com/tj/co
gm Image processing library https://github.com/aheckmann/gm
ali-oss OSS https://github.com/ali-sdk/ali-oss
aliyun-sdk Alibaba Cloud https://github.com/aliyun-UED/aliyun-sdk-js
@alicloud/fc2 Function Compute https://github.com/aliyun/fc-nodejs-sdk
opencv OpenCV https://github.com/peterbraden/node-opencv

The following example uses wand to rotate an image:

  1. var gm = require('gm').subClass({ imageMagick: true });
  2. exports.handler = function (event, context, callback) {
  3. gm(event)
  4. .flip()
  5. .toBuffer('PNG', function (err, buffer) {
  6. if (err) return callback(err);
  7. callback(null, buffer);
  8. });
  9. };

Note: The event parameter in the preceding function is used as the binary data of an image. The image generated subsequently is also returned in the form of binary data.

Use custom modules

If you must use a custom module, the module must be packaged with the code. For example, to add a module mysql to access MySQL using the command-line tool fcli, follow these steps:

  1. Create a directory for storing code and the dependent module.

    1. mkdir /tmp/code
  2. Create a code file named index.js and save it to the /tmp/code directory. Enter mysql in the code.

    1. var mysql = require('mysql');
    2. exports.handler = function(event, context, callback) {
    3. var connection = mysql.createConnection({
    4. host : 'localhost',
    5. user : 'me',
    6. password : 'secret',
    7. database : 'my_db'
    8. });
    9. connection.connect();
    10. connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
    11. if (error) return callback(error);
    12. console.log('The solution is: ', results[0].solution);
    13. callback(null, results[0].solution);
    14. });
    15. connection.end();
    16. };
  3. Install the dependency in the /tmp/code directory.

    1. cd /tmp/code
    2. npm install mysql

    After the dependency is installed, the following information is displayed in the /tmp/code directory:

    1. ls -l /tmp/code
    2. -rw-r--r-- 1 rockuw wheel 511 Aug 15 17:58 index.js
    3. drwxr-xr-x 13 rockuw wheel 442 Aug 15 18:01 node_modules
  4. Use fcli to create and call a function.

    1. ./fcli shell
    2. mkf my-func -h index.handler --runtime nodejs6 -d /tmp/code
    3. invk my-func

Use external commands

Your function may use external tools that are not developed in Node.js. For example, your function may use shell scripts or executable files compiled from C++ or Go code. In this case, you can still package them with your code and then use them by running external commands in the functions. The following example demonstrates how to run a shell script:

  1. var exec = require('child_process');
  2. exports.handler = function(event, context, callback) {
  3. var scriptPath = process.env['FC_FUNC_CODE_PATH'] + '/script.sh';
  4. exec.exec('bash '+scriptPath, {}, function(err, stdout, stderr) {
  5. if (err) return callback(err);
  6. console.log(stdout, stderr);
  7. callback(null, stdout);
  8. });
  9. };

Note: Executable files compiled from C, C++, or Go code must be compatible with the runtime environment of Function Compute. The following Node.js runtime environments are supported in Function Compute:

  • Linux kernel: Linux 4.4.24-2.al7.x86_64
  • Docker base image: Docker Pull Node: 6.10

Understand callbacks

Node.js uses an asynchronous programming model. Therefore, your function must call a callback to return data or errors. If no callbacks are used in your function, a message is displayed, indicating that function execution has timed out.

1. Make sure that a callback is called.

If a function does not call a callback, the system assumes that the function is still being called, and waits for the function result until the operation times out. For example, when the following function is called, a timeout error is returned:

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

After the preceding commands are run, the following output is displayed:

  1. {"errorMessage":"Function timed out after 3 seconds"}

2. Function execution ends after a callback is called

After a callback is called, function execution ends. If the callback is called multiple times, only the result of the first callback takes effect. Make sure that all tasks are completed before calling the callback again. Otherwise, the remaining tasks are not executed. For example, after the following function is executed, “hello world” is returned but no “message” is displayed.

  1. exports.handler = function(event, context, callback) {
  2. callback(null, 'hello world');
  3. callback(null, 'done');
  4. setTimeout(function() {
  5. console.log('message');
  6. }, 1000);
  7. };

Handle exceptions

After a function in the Node.js runtime environment is executed, you may receive the following errors. The error type is recorded in the returned HTTP Header field X-Fc-Error-Type.

  1. HandledInvocationError: error returned by the first callback parameter.
  2. UnhandledInvocationError: other errors, such as an uncaught exception, a timeout error, or an out-of-memory error.

Sample 1. Return HandledInvocationError error

  1. exports.handler = function(event, context, callback) {
  2. callback(new Error('oops'));
  3. };

After the callback is called, the following output is displayed:

  1. {
  2. "errorMessage": "oops",
  3. "errorType": "Error",
  4. "stackTrace": [
  5. "at exports.handler (/code/index.js:2:12)"
  6. ]
  7. }

Sample 2. Return UnhandledInvocationError error

  1. exports.handler = function(event, context, callback) {
  2. throw new Error('oops');
  3. };

After the callback is called, the following output is displayed:

  1. {"errorMessage":"Process exited unexpectedly before completing request"}

For more information about errors in Function Compute, see Error message.

Thank you! We've received your feedback.