AWS Lambda – Function in NODEJS


Advertisements

Nodejs is one of the languages that AWS Lambda function supports. The version supported with nodejs are v6.10 and v8.10. In this chapter, we will learn about various functionalities of AWS Lambda function in NODEJS in detail.

Handler in NodeJS

To writeAWS Lambda function in nodejs, we should first declare a handler first. The handler in nodejs is name of the file and the name of the export function. For Example, the name of the file is index.js and the export function name is lambda handler, so its corresponding handler is index.lambdahandler

Observe a sample handler shown here −

exports.lambdahandler = function(event, context, callback) {   //code goes here}

Params to Handler

Handler is the main core for building Lambda function. The handler takes three params: event, context and callback.

Event Parameter

It has all the details of the event triggered. For Example, if we are using Lambda function to be triggered on S3, the event will have details of the S3 object.

Context Parameter

It has the details of the context such as the properties and configuration details of the Lambda function.

Callback Function

It helps in giving details back to the caller. The structure of callback looks as follows −

callback(error, result);

The parameters of callback function are explained given below −

Error − This will have details if any error has occurred during the execution of Lambda function. If the Lambda function succeeds,null can be passed as the first param for callback function.

Result − This will give the details of the successful execution of the lambda function. If an error occurs, the result param is ignored.

Note − It is not mandatory to use the callback function in AWS Lambda. Incase if there is no callback function, the handler will return it as null.

The valid callback signatures are given below −

callback();                // It will return success, but no indication to the caller
callback(null);            // It will return success, but no indication to the caller
callback(null, "success"); // It will return the success indication to the caller
callback(error);           //  It will return the error indication to the caller

Whenever AWS Lambda gets executed the callback details such as error or success, are logged in AWS CloudWatch along with console messages, if any.

Working with AWS Lambda in Nodejs8.10

Let us understand how to work with AWS Lambda in nodejs8.10 and invoke the function in sync and async way.

Invoking Lambda Function in Sync Way

The following example gives you an idea about invoking Lambda function in sync way −

exports.handler = function(event, context, callback) {
   let arrItems = [4,5,6,8,9,10,35,70,80,31];
   function countevennumbers (items) {
      return new Promise(resolve => {
         setTimeout(() => {
            let a = 0;
            for (var i in items) {
               if (items[i] % 2 == 0) {
                  a++;
               } 
            }
            resolve(a);
         },2000);
      });
   }
   let evennumber = countevennumbers(arrItems);
   callback(null,'even numbers equals ='+evennumber);
};

You can observe the following output after testing this code in AWS console −

Even Number Count

Note that the output from the above code is a promise object. It does not give the count, as the count is incremented inside a setTimeout and the function call does not wait for the execution inside setTimeout and returns the promise object.

If we had async/await on the handler function will get exact output of from the lambda function.

Invoking the Handler in an Async Way

The following example gives you an idea about invoking Lambda function in an async way −

exports.handler = async function(event, context, callback) {
   let arrItems = [4,5,6,8,9,10,35,70,80,31];
   function countevennumbers (items) {
      return new Promise(resolve => {
         setTimeout(() => {
            let a = 0;
            for (var i in items) {
               if (items[i] % 2 == 0) {
                  a++;
               } 
            }
            resolve(a);
         }, 2000);
      });
   }
   let evennumber = await countevennumbers(arrItems);
   callback(null,'even numbers equals ='+evennumber);
};

We have added async and await in above code. When we use await beside the function call, the execution pauses till the promise inside the function gets resolved. Note that await is valid only for async functions.

You can observe the following output after testing this code in AWS console −

Even Number Count Output

ContextDetails in NodeJS

Context object gives details such as the name of the Lambda function, time remaining in milliseconds, request id, cloudwatch group name, timeout details etc.

The following tables shows the list of methods and attributes available with context object −

Method available for context object

Sr.No Method Name & Description
1

getRemainingTimeInMillis()

This method gives the remaining time in milliseconds until the Lambda function terminates the function

Attributes available for context object

Sr.No Attribute name & Description
1

functionName

This gives AWS Lambda function name

2

functionVersion

This gives the version of AWS Lambda function executing

3

nvokedFunctionArn

This will gives ARN details.

4

memoryLimitInMB

This shows the memory limit added while creating Lambda function

5

awsRequestId

This gives the AWS request id.

6

logGroupName

This will give the name of the cloudwatch group name

7

logStreamName

This will give the name of the cloudwatch log stream name where the logs are written.

8

identity

This will give details about amazon cognito identity provider when used with aws mobile sdk.

Details given are as follows −

  • identity.cognito_identity_id
  • identity.cognito_identity_pool_id
9

clientContext

This will details of the client application when used with aws mobile sdk. The details given are as follows −

  • client_context.client.installation_id
  • client_context.client.app_title
  • client_context.client.app_version_name
  • client_context.client.app_version_code
  • client_context.client.app_package_name
  • client_context.custom - it has dict of custom values from the mobile client app
  • client_context.env - it has environment details from the AWS Mobile SDK

Look at the following example to get a better idea about context object −

exports.handler = (event, context, callback) => {
   // TODO implement
   console.log('Remaining time =>', context.getRemainingTimeInMillis());
   console.log('functionName =>', context.functionName);
   console.log('AWSrequestID =>', context.awsRequestId);
   console.log('logGroupName =>', context.log_group_name);
   console.log('logStreamName =>', context.log_stream_name);
   console.log('clientContext =>', context.clientContext);
   callback(null, 'Name of aws Lambda is=>'+context.functionName);
};

You can observe the following output after testing this code in AWS console −

Succeeded Logs

You can observe the following log output after testing this code in AWS console −

Log Output Testing

Logging in NodeJS

We can use console.log for logging in NodeJS.The log details can be fetched from CloudWatch service against the Lambda function.

Observe the following example for a better understanding −

exports.handler = (event, context, callback) => {
   // TODO implement
   console.log('Logging for AWS Lamnda in NodeJS');
   callback(null, 'Name of aws Lambda is=>'+context.functionName);
};

You can observe the following output after testing this code in AWS console −

Output After Testing

You can observe the following screenshot from CloudWatch −

Screenshot Cloud Watch

Error Handling in NodeJS

Let us understand how error notification is done in NodeJS. Observe the following code −

exports.handler = function(event, context, callback) {
   // This Source code only throws error. 
   var error = new Error("something is wrong");
   callback(error);   
};

Execution Result Details

You can observe the following in the log output −

Log Output Observation

The error details are given in the callback as follows −

{
   "errorMessage": "something is wrong",
   "errorType": "Error",
   "stackTrace": [    "exports.handler (/var/task/index.js:2:17)"  ]
}
Advertisements