Getting Started With AWS Lambda

Part - 3 : Invoking Lambda function

Amazon AWS Lambda function



Overview

This is the third part of a 3-part tutorial series on Getting started with amazon Lambda :

  1. In this part, we already learned how we can create a user on our amazon AWS account.
  2. In the second part we already learned how we can create our first lambda function step by step.
  3. In the third part, we will code our lambda function and also we will create our node.js function to call our lambda function.
Prerequisites

  1. Amazon AWS account : You can create Amazon AWS account here or you can login to your account, if u already have one.
  2. User with Lambda full access : You can learn how to create a user with full lambda access here
  3. Access Key Pair :We got one while creating a user in Part-1 of this series.
  4. Location :Location on which our function is hosted. We noted it down in Step-7 Part-2 of this series.
  5. Node.js : Node.js Installed on your system.

Coding Lambda function

Let's start with lambda functions by creating a simple Hello World Program using Amazon AWS lambda functions. Copy the given code in the code editor on AWS as shown in the image below :

								
exports.handler = async (event) => {
    var message = "Hello from Nodejsera! This is a Lambda function"
    return message;
};

								
							

Your function will look something like :

amazon aws lambda function using node.js

Invoking Lambda function using node.js

Now We need to access the lambda function using node.js.Copy the given code in a .js :

								
//Name of the file : aws-lambda-hello.js
var AWS = require('aws-sdk');

AWS.config.update({accessKeyId: 'Your Access Key', secretAccessKey: 'Your Access Key Secret',region:'Location',});

var lambda = new AWS.Lambda();
var params = {
  FunctionName: 'helloWorld', /* Name of Your Lambda Function */
  Payload: JSON.stringify({}) /* Empty */
};
lambda.invoke(params, function(err, data) {
  if (err) console.log(err, err.stack); // Error
  else     console.log(data);           // Success
});
								
							

Run

We can run our code using the following command :

											
>node aws-lambda-hello.js
{ StatusCode: 200,
  ExecutedVersion: '$LATEST',
  Payload: '"Hello from Nodejsera! This is a Lambda function"' }

											
										

Summary

In this part of the Getting started with AWS lambda functions, we learned how we can code a lambda function. We also learned how to invoke a lambda function using node.js