I have this code in Lambda funcion:
sql="SELECT ...";
var pg = require('pg');
var connectionString = 'postgres://...';
var client = new pg.Client(connectionString);
client.connect();
var query = client.query(sql);
query.on('end', function() { client.end(); });
When I run from EC2, it works fine. When I run from Lambda I get Error: Cannot find module 'pg'
Lambda can work seamlessly with RDS instances, as long as you remember the specific requirements for this particular setup. Since RDS instances are running in your VPC and Lambda by default does not have access to those resources, you'll need to configure the VPC connection when creating a Lambda function.
I am a super noob in Node JS, but I really wanted to try AWS Lambda. Here are the steps I took. I used a Ubuntu 14.04.
sudo apt-get update
sudo apt-get install nodejs
sudo apt-get install npm
sudo ln -s /usr/bin/nodejs /usr/bin/node
mkdir the_function && cd the_function
mkdir node_modules
npm install pg
******Now create a file index.js and paste the content of your funcion.
console.log('Loading S2 Function');
var pg = require("pg");
exports.handler = function(event, context) {
var conn = "pg://user:password@host:5432/bd_name";
var client = new pg.Client(conn);
client.connect();
var query = client.query("SELECT * FROM BLA WHERE ID = 1");
query.on("row", function (row, result) {
result.addRow(row);
});
query.on("end", function (result) {
var jsonString = JSON.stringify(result.rows);
var jsonObj = JSON.parse(jsonString);
console.log(jsonString);
client.end();
context.succeed(jsonObj);
});
};
******Now zip the contents of the_function folder (not the_function folder itself)
You can check the official sample from this AWS link: http://docs.aws.amazon.com/lambda/latest/dg/walkthrough-s3-events-adminuser-create-test-function-create-function.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With