I am using the code below to write a log file to AWS S3 using AWS Lambda. It works sometimes but not others (50% success rate) and I can't understand why. Can anybody help?
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
exports.handler = async (event) => {
let key = 'log.' Date.now() '.txt'
let data = 'How are you?'
put_object('test', key, data).then((e) => { console.log(e) })
}
let put_object = async (bucket, file, data) => {
return await new Promise((resolve, reject) => {
const params = {
Body: data,
Bucket: bucket,
Key: file,
ACL: "public-read",
ContentType: "text/html"
}
s3.putObject(params, (err, results) => {
if (err) reject(err);
else resolve(results);
})
})
}
Edit....................
Thanks to @steadweb this function is totally reliable.
const AWS = require('aws-sdk')
const s3 = new AWS.S3()
exports.handler = async (event) => {
let key = 'log.' Date.now() '.txt'
let data = 'How are you?'
await put_object('test', key, data).then((e) => { console.log(e) })
}
let put_object = async (bucket, file, data) => {
return await new Promise((resolve, reject) => {
const params = {
Body: data,
Bucket: bucket,
Key: file,
ACL: "public-read",
ContentType: "text/html"
}
s3.putObject(params, (err, results) => {
if (err) reject(err);
else resolve(results);
})
})
}
CodePudding user response:
Most likely, your lambda is stopping before your async call has completed.
You'll need to await
your call to put_object
in order for it to complete successfully. As below
await put_object('test', key, data);