0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Hello Worldを出力するLambda関数のサンプルjavascriptをローカルで動かしてみた【Node.js】

0
Posted at

記事のテーマ

AWSのアカウントが無いのでローカルで動かしてみた。
Lambda関数に渡される引数のイメージが分かりやすく、意外と収穫があったので共有する。

使用したサンプルスクリプト(index.mjs)は以下。

構造

通常
イベント(AWS EventBridge等)
   ↓
AWS Lambda
   ↓
index.mjs ---> handler(event, context)
本記事で実施したこと
test.mjs
   ↓
index.mjs ---> handler(event, context)

実行環境

$ cat /proc/version 
MINGW64_NT-10.0-26200 version 3.6.7-fb42d713.x86_64 (@runnervm3zftq) (gcc version 15.2.0 (GCC) ) 2026-03-29 11:44 UTC
$ node -v
v24.18.0

実装

index.mjs
// AWS Lambda デベロッパーガイドのサンプルコード
// https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/getting-started.html
// 若干アレンジあり

// handler関数(Lambdaを実行すると最初に実行される関数) 
// 外部サービスであるLambdaから呼び出されるのでexportしておく必要がある
// アロー関数で表記されている
// Lambdaは非同期処理(API呼び出しやDBアクセス)が多いため、公式サンプルでもasyncが使われていると思われる
// このサンプルのような単純な処理では不要
export const handler = async (event, context) => {
// 通常の関数で表記するなら以下
// export const handler = function async (event, context) {
  
  // Lambdaであれば[Event JSON] セクションから引数を受け取る
  // 今回は呼び出し元のtest.mjsから受け取る
  const length = event.length;
  const width = event.width;

  // 面積算出関数呼び出し
  let area = calculateArea(length, width);
  
  // 求めた面積をログ出力する
  console.log(`The area is ${area}`);
        
  // Lambdaランタイムが実行時にhandler関数にcontextを渡す
  // 今回は呼び出し元のtest.mjsがcontextを渡す
  // logGroupName - 関数のロググループ
  console.log('CloudWatch log group: ', context.logGroupName);
  
  // レスポンス返却する
  return {
    statusCode: 200,
    body: JSON.stringify({
      area,
      message: "Hello from Lambda!"
    })
  };
    
  // 面積算出関数
  function calculateArea(length, width) {
    return length * width;
  }
};
test.mjs
// 本来であればこのクラスの処理はLambdaが行う
// index.mjsを呼び出すクラスを実装してみることで、Lambdaが関数に引数を渡す処理イメージが湧きやすい

// index.mjsでexportしたhandler関数をimportする
import { handler } from "./index.mjs";

// Lambdaの場合、[Event JSON] セクションで設定する
// ここでは手動でeventオブジェクトを設定する
const event = {
  length: 10,
  width: 5
};

// Lambdaの場合、Lambda関数を実行すると自動でLambdaがLambda関数にcontextオブジェクトを渡す
// ここでは手動でcontextオブジェクトを設定する
// contextオブジェクトのプロパティはいくつもあるが、ここではサンプルとしてlogGroupName - 関数のロググループを使用する
const context = {
  logGroupName: "local-test",
};

// handler関数を実行する
const result = await handler(event, context);

// 実行結果をログ出力する
console.log(result);

実行結果

$ node test.mjs 
The area is 50
CloudWatch log group:  local-test
{ statusCode: 200, body: '{"area":50,"message":"Hello from Lambda!"}' }

所感

謎の引数eventcontextを見える化できた。
ローカルで動かしても意味無いかと思ったけど、試してみてよかった。

0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?