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 のログ」をご参照ください。
exports.handler = function (event, context, callback) {
console.info(null, 'hello world');
callback(null, 'hello world');
};
前述のコマンドを実行すると、次の結果が表示されます。
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
です。
'use strict';
exports.handler = function(evt, ctx, cb) {
console.setLogLevel("error");
console.error("console error 1");
console.info("console info 1");
console.warn("console warn 1");
console.log("console log 1");
console.setLogLevel("warn");
console.error("console error 2");
console.info("console info 2");
console.warn("console warn 2");
console.log("console log 2");
console.setLogLevel("info");
cb(null, evt);
};
前述のコマンドを実行すると、次の結果が表示されます。
message:2017-07-05T05:13:35.920Z a72df088-f738-cee3-e0fe-323ad89118e5 [ERROR] console error 1
message:2017-07-05T05:13:35.920Z a72df088-f738-cee3-e0fe-323ad89118e5 [ERROR] console error 2
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 を使用しています。
var gm = require('gm').subClass({ imageMagick: true });
exports.handler = function (event, context, callback) {
gm(event)
.flip()
.toBuffer('PNG', function (err, buffer) {
if (err) return callback(err);
callback(null, buffer);
});
};
注意:上記の関数の
event
パラメーターは、画像のバイナリデータとして使用されます。その後に生成される画像も、バイナリデータの形式で返されます。
カスタムモジュールの使用
カスタムモジュールを使用する必要がある場合は、モジュールをコードと一緒にパッケージ化する必要があります。たとえば、コマンドラインツール fcli を使用して MySQL にアクセスするモジュール mysql を追加するには、次の手順を実行します。
コードと依存モジュールを格納するディレクトリを作成します。
mkdir /tmp/code
index.js という名前のコードファイルを作成し、/tmp/code ディレクトリに保存します。コードに
mysql
と入力します。var mysql = require('mysql');
exports.handler = function(event, context, callback) {
var connection = mysql.createConnection({
host : 'localhost',
user : 'me',
password : 'secret',
database : 'my_db'
});
connection.connect();
connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
if (error) return callback(error);
console.log('The solution is: ', results[0].solution);
callback(null, results[0].solution);
});
connection.end();
};
/tmp/code ディレクトリに依存関係をインストールします。
cd /tmp/code
npm install mysql
依存関係がインストールされると、以下の情報が
/tmp/code
ディレクトリに表示されます。ls -l /tmp/code
-rw-r--r-- 1 rockuw wheel 511 Aug 15 17:58 index.js
drwxr-xr-x 13 rockuw wheel 442 Aug 15 18:01 node_modules
fcli を使用して、関数を作成して呼び出します。
./fcli shell
mkf my-func -h index.handler --runtime nodejs6 -d /tmp/code
invk my-func
外部コマンドの使用
Node.js で開発されていない外部ツールを、関数で使用することがあります。たとえば、C++ や Go コードでコンパイルされた shell スクリプトや、実行ファイルを使用するかもしれません。この場合、コードと一緒にパッケージ化し、関数内で外部コマンドを実行して使用することができます。次の例は、shell スクリプトを実行する方法を示しています。
var exec = require('child_process');
exports.handler = function(event, context, callback) {
var scriptPath = process.env['FC_FUNC_CODE_PATH'] + '/script.sh';
exec.exec('bash '+scriptPath, {}, function(err, stdout, stderr) {
if (err) return callback(err);
console.log(stdout, stderr);
callback(null, stdout);
});
};
注意: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 が関数で呼び出されない場合、システムは関数が終了しないとみなし、関数の結果がタイムアウトするまで待ちます。たとえば、次の関数が呼び出されると、タイムアウトエラーが返されます。
exports.handler = function(event, context, callback) {
console.log('hello world');
};
前述のコマンドを実行すると、次の結果が表示されます。
{"errorMessage":"Function timed out after 3 seconds"}
2. callback が呼び出された後、関数の実行が終了する
callback が呼び出されると、関数の実行が終了します。callback が繰り返し呼び出されると、最初の callback の結果のみが有効になります。callback を再度呼び出す前に、すべてのタスクが完了していることを確認してください。そうしないと、残りのタスクは実行されません。たとえば、次の関数を実行すると、 “hello world” が返されますが、”message” は表示されません。
exports.handler = function(event, context, callback) {
callback(null, 'hello world');
callback(null, 'done');
setTimeout(function() {
console.log('message');
}, 1000);
};
例外処理
Node.js ランタイム環境の関数を実行すると、次のエラーが発生することがあります。エラータイプは、返された HTTP ヘッダフィールド X-Fc-Error-Type
に記録されます。
HandledInvocationError
:最初の callback パラメーターによって返されるエラーです。UnhandledInvocationError
:キャッチされない例外、タイムアウトエラー、またはメモリ不足エラーなどその他のエラーです。
サンプル 1. HandledInvocationError
エラーを返す
exports.handler = function(event, context, callback) {
callback(new Error('oops'));
};
callback が呼び出されると、次の結果が表示されます。
{
"errorMessage": "oops",
"errorType": "Error",
"stackTrace": [
"at exports.handler (/code/index.js:2:12)"
]
}
サンプル 2. UnhandledInvocationError
エラーを返す
exports.handler = function(event, context, callback) {
throw new Error('oops');
};
callback が呼び出されると、次の結果が表示されます。
{"errorMessage":"Process exited unexpectedly before completing request"}
Function Compute のエラーの詳細については、「エラーメッセージ」をご参照ください。