简体   繁体   中英

AWS Lambda function to updload json to s3 bucket not working

When I run this function, it says that it succeeds, but the file is not in the s3 bucket.

var AWS = require('aws-sdk');
exports.handler = (event, context, callback) => {

    AWS.config.update({
        region: 'us-west-2',
        accessKeyId: 'xxx',
        secretAccessKey: 'xxx'
    });

    var s3 = new AWS.S3();

    s3.putObject({
        Bucket: 'mybucket',
        Key: 'test.json',
        Body: [{test: 'test'}, {test: 'test'}],
        ContentType: "application/json"
    }, function(){});

    context.succeed('SUCCESS');
};

NodeJs is a interesting language.

Most languages would process your code like this

  1. AWS.config.update({..})
  2. var s3 = ..
  3. s3.putObject(.., callback); (This takes time, so it would wait till it finishes)
  4. context.succeed(..)

Node js will process in this order.

  1. AWS.config.update({..})
  2. var s3 = ..
  3. s3.putObject(.., callback); (This takes time, so I will go to next step)
  4. context.succeed(..)
  5. the s3.putObject(.., callback) has finished. I'll call the callback now.
  6. callback(err, res). It calls the callback with the error. Since your program has an empty callback, function(){}, it will not do anything with the error and you won't know about it.
 var AWS = require('aws-sdk'); exports.handler = (event, context, callback) => { AWS.config.update({ region: 'us-west-2', accessKeyId: 'xxx', secretAccessKey: 'xxx' }); var s3 = new AWS.S3(); s3.putObject( { Bucket: 'mybucket', Key: 'test.json', Body: [{test: 'test'}, {test: 'test'}], ContentType: "application/json" }, function(err, res){ if(err){ console.log(err); } callback(err, "processed"); }); }; 

^The callback will tell lambda that it is the end of the script. It will now process like this.

  1. AWS.config.update({..})
  2. var s3 = ..
  3. s3.putObject(.., callback); (This takes time, but there isn't another step so I'll wait)
  4. the s3.putObject(.., callback) has finished. I'll call the callback now.
  5. callback(err, res). It calls the callback with the error. You will print the error and be able to debug your program.
  6. callback(err, 'processed') will end the lambda.

您可以使用Q https://www.npmjs.com/package/q或NodeJs promises以要求的顺序处理任务。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM