The Scenario
I am learning about AWS Lambda functions and doing a small tutorial that works through using the lambda-canary blueprint which uses python 2.7
The Problem
I want to do this same canary function in Node.js 6.10, but I could not find out how to do this.
The solution
Below is the code sample that I came up with to implement the lambda-canary-nodejs lambda function
var http = require('http'); exports.handler = (event, context, callback) => { var site = process.env['site']; var expected = process.env['expected']; console.log('Checking website: ' + site); http.get(site, (resp) => { let body = ''; // read the data resp.on('data', (chunk) => {body += chunk; }); // The whole response has been received. resp.on('end', () => { // validate that the expected value is in the returned stream if(body.indexOf(expected) > 0){ console.log('website is up') callback(null, event['time']); } else { console.log('website did not respond as expected') var error = new Error('website did not respond as expected'); callback(error); } }); }).on("error", (err) => { console.log("Error: " + err.message); callback(err); }); };
Items to note about this code:
- process.env[‘key’] is how you access the environment varialbes/li>
- environment variables are case sensitive, so the string index must match variable name as defined on the lambda function
- callback accepts an error object as the first parameter when it fails
So to implement this you would:
- Create a new blank function
- Past in this code
- Setup 2 x environment variables, site & expected
- Create a test of type scheduled event
- Test the code