rlcrews
rlcrews

Reputation: 3562

How to create a file in Amazon S3 Node Lambda function

I am trying to create and load an object into an s3 container but the PUT event does not seem to create the object

const AWS = require('aws-sdk');
const fs = require('fs');
const s3 = new AWS.S3();

exports.handler = async (event) => {
    // I've tried the full arn as well as just the bucket name 
    const bucket ='someBucketName';
    const key = 'sample.csv';
    // for testing purposes I am just loading a 30 row csv file.
    // I've also tried a json object with no luck
    // ex: const data = JSON.stringify({'label': 'foo'});

    const data = fs.readFileSync('trees.csv','utf-8');

    const params ={
        Bucket : bucket,
        Key : key,
        Body: data
    };
    await s3.putObject(params, function (err, data) {
        if(err){
            console.log(`Error creating file ${err.stack}`);
        }else{
            console.log('File Created');
        }
    });
};

When I execute the lambda it runs with no errors. But no file is ever created in the bucket and I never see the output of 'File Created'. If I add a console.log() prior to the put I can see the params are all set. The lambda has full s3 access as well as full access to cloudWatch. This is just a test so I am running it directly from the lambda console in aws.

Any suggestions on what I am missing or doing wrong?

Upvotes: 2

Views: 1108

Answers (1)

rlcrews
rlcrews

Reputation: 3562

Found the answer for those interested. I omitted the promise() on the putObject function.

const AWS = require('aws-sdk');
const fs = require('fs');
const s3 = new AWS.S3();

exports.handler = async (event) => {
    const bucket ='someBucketName';
    const key = 'sample.csv';    
    const data = fs.readFileSync('trees.csv','utf-8');

    const params ={
        Bucket : bucket,
        Key : key,
        Body: data
    };
    await s3.putObject(params, function (err, data) {
        if(err){
            console.log(`Error creating file ${err.stack}`);
        }else{
            console.log('File Created');
        }
    }).promise();
};

Upvotes: 3

Related Questions