Node.js - S3 examples within async functions
A simple get object example within an async
function.
(async function() {
const AWS = require("aws-sdk");
const s3 = new AWS.S3();
let results;
try {
const s3Result = await s3.getObject({
Bucket: "bucketname",
Key: "key"
}).promise();
results = s3Result.Body.toString("utf8");
} catch (e) {
console.error(`Could not retrieve from S3: ${e.message}`);
results = "";
}
console.log(results);
})();
Put object example.
(async function() {
const AWS = require("aws-sdk");
const s3 = new AWS.S3();
try {
await s3.putObject({
Body: "Some text",
Bucket: "bucketname",
Key: "key",
ContentType: "text/plain"
}).promise();
console.log("Saved to S3");
} catch (e) {
console.error(`Could not save to S3: ${e.message}`);
}
})();
List objects example.
(async function() {
const AWS = require("aws-sdk");
const s3 = new AWS.S3();
try {
const data = await s3.listObjects({
Bucket: "bucketname",
MaxKeys: 1000,
Prefix: ""
}).promise();
console.log(`Listing ${data.Contents.length} object(s) in bucket with prefix`);
for (const object of data.Contents) {
console.log(object.Key);
}
} catch (e) {
console.error(`Could not list objects: ${e.message}`);
}
})();
Delete object example.
(async function() {
const AWS = require("aws-sdk");
const s3 = new AWS.S3();
try {
await s3.deleteObject({
Bucket: "bucketname",
Key: "key"
}).promise();
console.log("Deleted object in S3");
} catch (e) {
console.error(`Could not delete object in S3: ${e.message}`);
}
})();