forked from awsdocs/aws-doc-sdk-examples
-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
JavaScript (v3): S3 - Add 'delete all objects' scenario. (awsdocs#6812)
- Loading branch information
Showing
3 changed files
with
90 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
60 changes: 60 additions & 0 deletions
60
javascriptv3/example_code/s3/scenarios/delete-all-objects.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,60 @@ | ||
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
import { | ||
DeleteObjectsCommand, | ||
paginateListObjectsV2, | ||
S3Client, | ||
} from "@aws-sdk/client-s3"; | ||
|
||
/** | ||
* | ||
* @param {{ bucketName: string }} config | ||
*/ | ||
export const main = async ({ bucketName }) => { | ||
const client = new S3Client({}); | ||
try { | ||
console.log(`Deleting all objects in bucket: ${bucketName}`); | ||
|
||
const paginator = paginateListObjectsV2( | ||
{ client }, | ||
{ | ||
Bucket: bucketName, | ||
}, | ||
); | ||
|
||
const objectKeys = []; | ||
for await (const { Contents } of paginator) { | ||
objectKeys.push(...Contents.map((obj) => ({ Key: obj.Key }))); | ||
} | ||
|
||
const deleteCommand = new DeleteObjectsCommand({ | ||
Bucket: bucketName, | ||
Delete: { Objects: objectKeys }, | ||
}); | ||
|
||
await client.send(deleteCommand); | ||
|
||
console.log(`All objects deleted from bucket: ${bucketName}`); | ||
} catch (caught) { | ||
if (caught instanceof Error) { | ||
console.error( | ||
`Failed to empty ${bucketName}. ${caught.name}: ${caught.message}`, | ||
); | ||
} | ||
} | ||
}; | ||
|
||
// Call function if run directly. | ||
import { fileURLToPath } from "url"; | ||
import { parseArgs } from "util"; | ||
if (process.argv[1] === fileURLToPath(import.meta.url)) { | ||
const options = { | ||
bucketName: { | ||
type: "string", | ||
}, | ||
}; | ||
|
||
const { values } = parseArgs({ options }); | ||
main(values); | ||
} |