How can I delete folder on s3 with node.js?

后端 未结 7 1265
误落风尘
误落风尘 2021-01-30 10:48

Yes, I know. There is no folder concept on s3 storage. but I really want to delete a specific folder from s3 with node.js. I tried two solutions, but both didn\'t work. My code

7条回答
  •  自闭症患者
    2021-01-30 11:12

    The accepted answer throws an error when used in typescript, and it is do Objects array in deleteParams. I made it work by modifying the code in the following way. I'm very new to Typescript but at least it is working now.

     async function emptyS3Directory(prefix: string) {
      const listParams = {
        Bucket: "bucketName",
        Prefix: prefix, // ex. path/to/folder
      };
    
      const listedObjects = await s3.listObjectsV2(listParams).promise();
    
      if (listedObjects.Contents.length === 0) return;
    
      const deleteParams = {
        Bucket: bucketName,
        Delete: { Objects: [] as any },
      };
    
      listedObjects.Contents.forEach((content: any) => {
        deleteParams.Delete.Objects.push({ Key: content.Key });
      });
    
      await s3.deleteObjects(deleteParams).promise();
    
      if (listedObjects.IsTruncated) await emptyS3Directory(prefix);
    }
    

提交回复
热议问题