如何将node.js文件上载到AWS Lambda并成功运行?

时间:2017-06-15 03:40:42

标签: node.js amazon-web-services amazon-ec2 aws-lambda

console.log('starting function')
exports.handle = function(event, context, callback){

  var firebase = require('firebase');
  var admin = require("firebase-admin");
  var Mixpanel = require('mixpanel');

  // initialize mixpanel client configured to communicate over https
  var mixpanel = Mixpanel.init('********************', {
  protocol: 'https'
  });

  var serviceAccount = require("productionKey.json");
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "********************"
  });

  function getTotalUsers(){
    admin.database().ref("users").once('value').then(function(snapshot) {
      console.log("Total Users:", snapshot.numChildren());
      mixpanel.track('Users Calculated', {
        distinct_id: '9999',
        "Total Users": snapshot.numChildren()
      });
      callback(null, snapshot.numChildren());
    });
  }

  getTotalUsers();
}

我的问题是如何在AWS Lambda中实际运行和运行?我添加了前两行和回调,因为我认为这是AWS所必需的。我是新手,但是我的脚本在没有这些元素的情况下工作正常。我压缩组件,包括模块和package.json以及firebase生成密钥,并将其作为Lambda函数上传,当我测试它时,无论我将最大超时更改为什么,它都会超时。

我做错了什么?我写了大量的node.js脚本与这些脚本并不太相似,我很想知道如何让它们在AWS Lambda(预定)上运行。非常感谢你的帮助!

1 个答案:

答案 0 :(得分:1)

Lambda函数不像脚本一样运行。他们设置并导出处理函数,Lambda调用它。容器通常会持久存在,Lambda会在后续(但不是并发)调用中初始化所有内容时重新调用处理程序。

未经测试,但为了给您提供这个想法,您的代码的高级Lambdafication可能看起来更像这样:

  console.log('starting initialization')


  var firebase = require('firebase');
  var admin = require("firebase-admin");
  var Mixpanel = require('mixpanel');

  // initialize mixpanel client configured to communicate over https
  var mixpanel = Mixpanel.init('********************', {
  protocol: 'https'
  });

  var serviceAccount = require("productionKey.json");
  admin.initializeApp({
    credential: admin.credential.cert(serviceAccount),
    databaseURL: "********************"
  });

  exports.handler = function(event, context, callback) => {

    console.log('function invoked');

    // google this -- you probably need this set to false, default is true 
    context.callbackWaitsForEmptyEventLoop = false;

    admin.database().ref("users").once('value').then(function(snapshot) {
      console.log("Total Users:", snapshot.numChildren());
      mixpanel.track('Users Calculated', {
        distinct_id: '9999',
        "Total Users": snapshot.numChildren()
      }); 
      callback(null, snapshot.numChildren());
    });

  };