AWS Lambda – Function in NODEJS
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 NodeJSTo 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}
Handler is the main core for building Lambda function. The handler takes three params: event, context and callback.
Event ParameterIt 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 ParameterIt has the details of the context such as the properties and configuration details of the Lambda function.
Callback FunctionIt 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.10Let 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 WayThe 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 −
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 WayThe 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 −
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- 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 −
You can observe the following log output after testing this code in AWS console −
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 −
You can observe the following screenshot from CloudWatch −
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); };
You can observe the following in the log output −
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)" ] }
Comments
Post a Comment