如何使用Node.js从AWS Lambda中的/ tmp文件夹将WAV文件上载到S3

时间:2018-04-28 02:14:57

标签: amazon-web-services amazon-s3 aws-lambda

我已成功创建AWS Lambda函数以使用sox处理某些音频并将结果存储到/ tmp文件夹。我想将结果文件上传到S3。我尝试了多种方法,但没有让它起作用。这是我的功能:

const lambdaAudio = require('lambda-audio')
const fs = require('fs')

exports.handler = function(event, context) {

  lambdaAudio.sox('./input.mp3 -c 1 /tmp/output.wav')
    .then(response => {
        if (fs.existsSync('/tmp/output.wav')) {
              console.log('output.wav file exists.')  // This works!

              // UPLOAD TO S3 HERE  HOW???

        }            
    })
    .catch(errorResponse => {
      console.log('Error from the sox command:', errorResponse)
    })
}

更新 这是我的最终工作版本,其中包含了dpwrussell的答案:

var lambdaAudio = require('lambda-audio')
var fs = require('fs')
var AWS = require('aws-sdk');

var accessKeyId =  "xxxxxxxxxxxxxxxxxxxxx";
var secretAccessKey = "xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";

AWS.config.update({
  accessKeyId: accessKeyId,
  secretAccessKey: secretAccessKey
});

exports.handler = function(event, context) {

  lambdaAudio.sox('./input.mp3 -c 1 /tmp/output.wav')
    .then(response => {
        if (fs.existsSync('/tmp/output.wav')) {
              console.log('output.wav file exists.')  

              uploadToS3();

        }            
    })
    .catch(errorResponse => {
      console.log('Error from the sox command:', errorResponse)
    })
}

function uploadToS3() {
  fs.readFile('/tmp/output.wav', function (err, data) {
    if (err) { throw err; }

    var base64data = new Buffer(data, 'binary');

    var s3 = new AWS.S3();
    s3.putObject({
      Bucket: 'my-bucket',
      Key: 'output.wav',
      Body: base64data
    },function (resp) {
      console.log('Done');
    });

  });
}

1 个答案:

答案 0 :(得分:1)

只需使用S3 API即可。 lamba函数角色需要权限才能上传到此S3存储桶。

var AWS = require('aws-sdk');
fs.readFile('/tmp/output.wav', function (err, data) {
  if (err) { throw err; }

  var base64data = new Buffer(data, 'binary');

  var s3 = new AWS.S3();
  s3.putObject({
    Bucket: 'mybucket',
    Key: 'output.wav'
    Body: base64data
  },function (resp) {
    console.log('Done');
  });

});