Question

How to delete a directory from spaces

Posted November 9, 2021 107 views
DigitalOcean Spaces

From your example ${BUCKET}.${REGION}.digitaloceanspaces.com/${OBJECT_KEY}

I’m storing directories that are a result of a ten-digit galleryID example: ${BUCKET}.${REGION}.digitaloceanspaces.com/32a0321241}

I thought this would work but it does not.
s3.delete(${BUCKET}.${REGION}.digitaloceanspaces.com/${galleryID}, (error, data)=> {})

How can I send a delete request using the example above?

I am using nodeJS with KoaJS

These answers are provided by our Community. If you find them useful, show some love by clicking the heart. If you run into issues leave a comment, or add your own answer to help others.

×
Submit an Answer
2 answers

Hello, @mrtonyq22

You can easily delete the directory from your DigitalOcean account as well.

Just navigate to the Space in your account and then click the “More” button and select Delete

https://docs.digitalocean.com/products/spaces/how-to/add-and-remove-files/

I personally use s3cmd to manage my Spaces due to the fact it is really user friendly. You can check this article in order to install s3cmd

https://docs.digitalocean.com/products/spaces/resources/s3cmd/

and check this mini tutorial on how to operate with s3cmd

https://www.digitalocean.com/community/questions/how-to-manage-digitalocean-spaces-using-s3cmd

An example command with s3cmd to delete a directory:

  • s3cmd del s3://newspace/test

Hope that this helps
Regards,
Alex

  • From my question: I am using nodeJS with KoaJS

    I am trying to somehowe use some API endpoint calls from a nodeJS app using JavaScript.

    Just like when I upload files below

     s3.upload(params, function (error, data) {})
    

    I want to be able to do also DELETE, PUT ETC.

     s3.delete(params, function (error, data) {})
     s3.put(params, function (error, data) {})
    
  • The following is not working and not only for me but other people to.

    I need help with the above ASAP. Support @DIGITAL OCEAN is horrible compare to other companies usually with in hours.

    s3.deleteObject(params, function (error, data) {
    if (error) {
    console.log(‘error: ’,error)
    }
    console.log(“Successfully deleted file”, data)
    return ctx.body = data
    })

I found the answer on StackOverflow for anyone interested.

async function emptyS3Directory(bucket, dir) {
    const listParams = {
        Bucket: bucket,
        Prefix: dir
    };

    const listedObjects = await s3.listObjectsV2(listParams).promise();

    if (listedObjects.Contents.length === 0) return;

    const deleteParams = {
        Bucket: bucket,
        Delete: { Objects: [] }
    };

    listedObjects.Contents.forEach(({ Key }) => {
        deleteParams.Delete.Objects.push({ Key });
    });

    await s3.deleteObjects(deleteParams).promise();

    if (listedObjects.IsTruncated) await emptyS3Directory(bucket, dir);
}

Call it

await emptyS3Directory(process.env.S3_BUCKET, 'images/')