すべてのプロダクト
Search
ドキュメントセンター

:Node.js ランタイム環境

最終更新日:Mar 20, 2020

Function Compute (FC) は現在、次の Node.js ランタイム環境をサポートしています。

  • Nodejs 6.10(runtime = nodejs6)
  • Nodejs 8.9.0(runtime = nodejs8)
  • Nodejs 10.15.3(runtime = nodejs10)

内容

このトピックでは、Node.js ランタイム環境の、以下の機能について説明します。

logging モジュールの使用

console.log を使用して関数が出力するデータは、サービスの作成時に指定された Logstore に収集されます。関数ログの詳細については、「Function Compute のログ」をご参照ください。

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

前述のコマンドを実行すると、次の結果が表示されます。

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

console.warn コマンドとconsole.error コマンドを実行すると、それぞれ WARN と ERROR のログエントリをパッケージ化できます。

setLogLevel を使用してログレベルを変更できます。次のログレベルは、優先順位の降順で表示されます。

  • error:対応するハンドラは console.error です。
  • warn:対応するハンドラは console.warn です。
  • info:対応するハンドラは console.info です。
  • verbose:対応するハンドラは console.log です。
  • debug:対応するハンドラは 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. };

前述のコマンドを実行すると、次の結果が表示されます。

  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

ビルトインモジュールの使用

標準の logging モジュールに加えて、Function Compute の Node.js ランタイム環境では、ユーザーがアクセスできるその他のモジュールを提供しています。現在、次の表に示すモジュールが使用可能です。

モジュール 説明 関連リンク
co 制御フロー https://github.com/tj/co
gm 画像処理ライブラリ 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
tablestore TableStore SDK https://github.com/aliyun/aliyun-tablestore-nodejs-sdk

次の例では、画像の回転に wand を使用しています。

  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. };

注意:上記の関数の event パラメーターは、画像のバイナリデータとして使用されます。その後に生成される画像も、バイナリデータの形式で返されます。

カスタムモジュールの使用

カスタムモジュールを使用する必要がある場合は、モジュールをコードと一緒にパッケージ化する必要があります。たとえば、コマンドラインツール fcli を使用して MySQL にアクセスするモジュール mysql を追加するには、次の手順を実行します。

  1. コードと依存モジュールを格納するディレクトリを作成します。

    1. mkdir /tmp/code
  2. index.js という名前のコードファイルを作成し、/tmp/code ディレクトリに保存します。コードに mysql と入力します。

    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. /tmp/code ディレクトリに依存関係をインストールします。

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

    依存関係がインストールされると、以下の情報が /tmp/code ディレクトリに表示されます。

    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. fcli を使用して、関数を作成して呼び出します。

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

外部コマンドの使用

Node.js で開発されていない外部ツールを、関数で使用することがあります。たとえば、C++ や Go コードでコンパイルされた shell スクリプトや、実行ファイルを使用するかもしれません。この場合、コードと一緒にパッケージ化し、関数内で外部コマンドを実行して使用することができます。次の例は、shell スクリプトを実行する方法を示しています。

  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. };

注意:C、C ++、または Go コードでコンパイルされた実行ファイルは、Function Compute のランタイム環境と互換性がなければなりません。Function Compute では、次の Node.js ランタイム環境をサポートしています。

  • Linux カーネル:Linux 4.4.24-2.al7.x86_64
  • Docker ベースイメージ:Docker Pull Node: 6.10

callback の理解

Node.js は、非同期プログラミングモデルを使用します。したがって関数は、データまたはエラーを返すために callback を呼び出す必要があります。関数で callback が使用されていない場合、関数の実行がタイムアウトしたことを示すメッセージが表示されます。

1. callback が呼び出されていることを確認する

callback が関数で呼び出されない場合、システムは関数が終了しないとみなし、関数の結果がタイムアウトするまで待ちます。たとえば、次の関数が呼び出されると、タイムアウトエラーが返されます。

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

前述のコマンドを実行すると、次の結果が表示されます。

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

2. callback が呼び出された後、関数の実行が終了する

callback が呼び出されると、関数の実行が終了します。callback が繰り返し呼び出されると、最初の callback の結果のみが有効になります。callback を再度呼び出す前に、すべてのタスクが完了していることを確認してください。そうしないと、残りのタスクは実行されません。たとえば、次の関数を実行すると、 “hello world” が返されますが、”message” は表示されません。

  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. };

例外処理

Node.js ランタイム環境の関数を実行すると、次のエラーが発生することがあります。エラータイプは、返された HTTP ヘッダフィールド X-Fc-Error-Type に記録されます。

  1. HandledInvocationError:最初の callback パラメーターによって返されるエラーです。
  2. UnhandledInvocationError:キャッチされない例外、タイムアウトエラー、またはメモリ不足エラーなどその他のエラーです。

サンプル 1. HandledInvocationError エラーを返す

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

callback が呼び出されると、次の結果が表示されます。

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

サンプル 2. UnhandledInvocationError エラーを返す

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

callback が呼び出されると、次の結果が表示されます。

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

Function Compute のエラーの詳細については、「エラーメッセージ」をご参照ください。