AJGarrett
5/13/2016 - 11:16 AM

AWS-Lambda-Example

AWS-Lambda-Example

// dependencies
var async = require('async');
var AWS = require('aws-sdk');
//var util = require('util');

// constants
var srcBucket = "staging.s3bucket.com";
var destBucket = "s3bucket.com";

// get reference to S3 client 
var s3 = new AWS.S3();
exports.handler = function(event, context, callback) {
    // Read options from the event.
    //console.log("Reading options from event:\n", util.inspect(event, {depth: 5}));
    var allKeys = [];
    
    function listAllKeys(marker, cb)
    {
      if (marker !== null) 
      {
          s3.listObjects({Bucket: srcBucket, Marker: marker}, function(err, data){
            allKeys.push(data.Contents);
            if(data.IsTruncated)
              listAllKeys(data.NextMarker, cb);
            else
              cb(allKeys);
          });
      } else {
          s3.listObjects({Bucket: srcBucket}, function(err, data){
            if(data.IsTruncated)
              listAllKeys(data.NextMarker, cb);
            else
              cb(data);
          });
          
      }    
        
    }
    
    listAllKeys(null,function(data) 
    { 
        if (data.Contents.length) {
            console.log(data.Contents.length);
            async.each(data.Contents, function(file, cb) {
                var params = {
                    Bucket: destBucket,
                    CopySource: srcBucket + '/' + file.Key,
                    Key: file.Key
                };
                s3.copyObject(params, function(copyErr, CopyData) {
                   if (copyErr) {
                       console.log(copyErr);
                   } else {
                       console.log('copied: ' + params.Key);
                       
                   }
                    
                });
            });
        }
        
    });
};