AWS Lambda - 下载一个文件,并在同一个函数中使用它 - nodejs

AWS Lambda - downloading a file, and using it in the same function - nodejs

我在 s3 (public) 上有一些证书文件,我要在我的代码中下载并使用这些文件,如果我在本地的 nodejs 中编写等效代码,它运行良好,但是在 AWS lambda 中它只是崩溃。

var apn = require('apn');
var https = require('https');
var fs = require('fs');

exports.handler = function(event, context) {
  console.log("Running aws apn push message function");
  console.log("==================================");
  console.log("event", event);

  var certPath = event.certPath;
  var keyPath = event.keyPath;
  var certFileName = event.certFileName;
  var keyFileName = event.keyFileName;
  var passphrase = event.passphrase;
  var apnId = event.apnId;
  var content = event.content;


var certfile = fs.createWriteStream(certFileName);
var certrequest = https.get(certPath, function(certresponse) {
  certresponse.pipe(certfile);
  console.log("downloaded the certificate");

  var keyfile = fs.createWriteStream(keyFileName);
  var keyrequest = https.get(keyPath, function(keyresponse) {
    keyresponse.pipe(keyfile);
    console.log("downloaded the key file");


  var options = { 
                      "cert":certFileName,
                      "key":keyFileName,
                      "passphrase":passphrase,
                      "batchFeedback": true,
                      "interval": 10
                      };

  var apnConnection = new apn.Connection(options);

  var myDevice = new apn.Device(apnId);
  var note = new apn.Notification();
  note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.        
  note.payload = {'COMMAND': content};       
  apnConnection.pushNotification(note, myDevice);
  console.log('message sent to ' + apnId);       

  context.done();

  });
});
}

我得到的错误与访问文件有关,我想 -

events.js:72 
 throw er; // Unhandled 'error' event 
 ^ 
Error: EACCES, open 'PushChatCert.pem'

因此,虽然在 AWS Lambda 上下载和使用文件时存在一些特定问题,与文件的路径或其他内容相关,文件下载后会保留在哪里,事实上我什至看不到下载文件的日志。

您可以在 Lambda 中写入的唯一可用本地文件系统是 /tmp,因此请确保您尝试写入的本地文件的路径位于 /tmp 目录中,并且您应该已准备就绪。

请注意,自去年(2020 年)起,Lambda 也支持将 EFS 作为挂载,因此您可以写入 EFS 挂载点。对你的情况来说太过分了……但它可能对处理大文件的人有帮助https://aws.amazon.com/blogs/compute/using-amazon-efs-for-aws-lambda-in-your-serverless-applications/