0
1

More than 3 years have passed since last update.

Node.js の Lambda 関数を ローカルでテストする

Last updated at Posted at 2017-12-08

Node.js の AWS Lambda 関数をローカルでテストする方法です。

テストで使う Lambda 関数

iot_aa.js
// ---------------------------------------------------------------
//  iot_aa.js
//
//                      Dec/08/2017
//
// ---------------------------------------------------------------
'use strict'

// ---------------------------------------------------------------
console.log('Loading function')

exports.iot_aa_handler = (event, context, callback) => {
    //console.log('Received event:', JSON.stringify(event, null, 2))
    console.log('value1 =', event.key1)
    console.log('value2 =', event.key2)
    console.log('value3 =', event.key3)
//
    const v1 = parseInt(event.key1)
    const v2 = parseInt(event.key2)
    const v3 = parseInt(event.key3)

    const sum = v1 + v2 + v3

    const version = "Version: Dec/08/2017 AM 09:25"
    var rvalue = {}
    rvalue['v1'] = v1
    rvalue['v2'] = v2
    rvalue['v3'] = v3
    rvalue['sum'] = sum
    rvalue['version'] = version
//
    callback(null, rvalue)  // Echo back the first key value

    //callback('Something went wrong')
}

// ---------------------------------------------------------------

テストに使うプログラム

test_local.js
#! /usr/bin/node
// ---------------------------------------------------------------
//  test_local.js
//
//                  Dec/08/2017
//
// ---------------------------------------------------------------
var fs = require("fs")
var iot_aa = require('./iot_aa')
// ---------------------------------------------------------------
console.error ("*** 開始 ***")

const event = {
    "key1": 11,
    "key2": 21,
    "key3": 31
}

const context = ""

iot_aa.iot_aa_handler(event,context,func01)


console.error ("*** 終了 ***")
// ---------------------------------------------------------------
function func01(aaa,rvalue)
{
    console.error ("*** func01 *** start ***")

    console.log(aaa)
    console.log(rvalue)

    console.error ("*** func01 *** end ***")
}
// ---------------------------------------------------------------

実行の様子
lambda_dec0801.png

テストの結果問題がなければ、次のスクリプトで、Lambda 関数の作成が出来ます。
ロールは変更して下さい。

#
FUNCTION='iot_aa'
ZIP_FILE=$FUNCTION".zip"
#
zip -r $ZIP_FILE $FUNCTION".js"

aws lambda create-function \
    --function-name $FUNCTION \
    --runtime nodejs12.x \
    --role arn:aws:iam::178234159025:role/role_bb \
    --handler $FUNCTION.iot_aa_handler \
    --zip-file fileb://$ZIP_FILE \
    --region ap-northeast-1
#

次のバージョンで動作を確認しました

$ node --version
v14.3.0
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1