You need to enable JavaScript to run this app.
导航
删除场景(Node.js SDK)
最近更新时间:2024.02.04 18:31:09首次发布时间:2023.12.19 18:47:28

本文介绍删除对象的常用场景代码。

删除目录

以下代码用于删除指定目录下 exampledir/ 的对象。

// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入
import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk';

// 创建客户端
const client = new TosClient({
  accessKeyId: process.env['TOS_ACCESS_KEY'],
  accessKeySecret: process.env['TOS_SECRET_KEY'],
  region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,则 "Provide your region" 填写为 cn-beijing。
  endpoint: "Provide your endpoint", // 填写域名地址
});

function handleError(error) {
  if (error instanceof TosClientError) {
    console.log('Client Err Msg:', error.message);
    console.log('Client Err Stack:', error.stack);
  } else if (error instanceof TosServerError) {
    console.log('Request ID:', error.requestId);
    console.log('Response Status Code:', error.statusCode);
    console.log('Response Header:', error.headers);
    console.log('Response Err Code:', error.code);
    console.log('Response Err Msg:', error.message);
  } else {
    console.log('unexpected exception, message: ', error);
  }
}

const bucketName = 'node-sdk-test-bucket';
async function main() {
  try {
    // 删除目录下所有文件
    const dir = 'exampledir/';
    for (let truncated = true, continuationToken = ''; truncated; ) {
      const { data } = await client.listObjectsType2({
        bucket: bucketName,
        maxKeys: 1000,
        continuationToken: continuationToken,
        prefix: dir,
      });

      for (const obj of data.Contents) {
        const { requestId } = await client.deleteObject({
          bucket: bucketName,
          key: obj.Key,
        });
        console.log('deleteObject %s Request ID:', obj.Key, requestId);
      }
      truncated = data.IsTruncated;
      continuationToken = data.NextContinuationToken;
    }
  } catch (error) {
    handleError(error);
  }
}

main();

清空桶

以下代码用于清空整个桶,包括删除所有对象、删除所有未合并的对象。

// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入
import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk';

// 创建客户端
const client = new TosClient({
  accessKeyId: process.env['TOS_ACCESS_KEY'],
  accessKeySecret: process.env['TOS_SECRET_KEY'],
  region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,则 "Provide your region" 填写为 cn-beijing。
  endpoint: "Provide your endpoint", // 填写域名地址
});

function handleError(error) {
  if (error instanceof TosClientError) {
    console.log('Client Err Msg:', error.message);
    console.log('Client Err Stack:', error.stack);
  } else if (error instanceof TosServerError) {
    console.log('Request ID:', error.requestId);
    console.log('Response Status Code:', error.statusCode);
    console.log('Response Header:', error.headers);
    console.log('Response Err Code:', error.code);
    console.log('Response Err Msg:', error.message);
  } else {
    console.log('unexpected exception, message: ', error);
  }
}

async function main() {
  try {
    const bucketName = 'node-sdk-test-bucket';

    // 删除桶中所有对象
    for (let isTruncated = true, continuationToken = ''; isTruncated; ) {
      const { data } = await client.listObjectsType2({
        maxKeys: 1000,
        bucket: bucketName,
        continuationToken,
      });

      // 删除对象
      for (const object of data.Contents) {
        const { requestId } = await client.deleteObject({
          bucket: bucketName,
          key: object.Key,
        });
        console.log('deleteObject %s Request ID:', object.Key, requestId);
      }

      isTruncated = data.IsTruncated;
      continuationToken = data.NextContinuationToken;
    }

    // 删除所有未合并的对象
    for (let isTruncated = true, keyMarker = '', uploadIdMarker = ''; isTruncated; ) {
      const { data } = await client.listMultipartUploads({
        bucket: bucketName,
        maxUploads: 1000,
        keyMarker,
        uploadIdMarker,
      });
      for (const upload of data.Uploads) {
        const { requestId } = await client.abortMultipartUpload({
          bucket: bucketName,
          key: upload.Key,
          uploadId: upload.UploadId,
        });
        console.log('abortMultipartUpload uploadId: %s, requestId: %s', upload.UploadId, requestId);
      }
      isTruncated = data.IsTruncated;
      keyMarker = data.NextKeyMarker;
      uploadIdMarker = data.NextUploadIdMarker;
    }
  } catch (error) {
    handleError(error);
  }
}

main();

清空开启多版本的桶

以下代码用于清空整个开启多版本桶的示例代码,包括删除所有对象的多个版本、删除删除标记的多个版本、删除所有未合并的对象。

// 导入 SDK, 当 TOS Node.JS SDK 版本小于 2.5.2 请把下方 TosClient 改成 TOS 导入
import { TosClient, TosClientError, TosServerError } from '@volcengine/tos-sdk';

// 创建客户端
const client = new TosClient({
  accessKeyId: process.env['TOS_ACCESS_KEY'],
  accessKeySecret: process.env['TOS_SECRET_KEY'],
  region: "Provide your region", // 填写 Bucket 所在地域。以华北2(北京)为例,则 "Provide your region" 填写为 cn-beijing。
  endpoint: "Provide your endpoint", // 填写域名地址
});

function handleError(error) {
  if (error instanceof TosClientError) {
    console.log('Client Err Msg:', error.message);
    console.log('Client Err Stack:', error.stack);
  } else if (error instanceof TosServerError) {
    console.log('Request ID:', error.requestId);
    console.log('Response Status Code:', error.statusCode);
    console.log('Response Header:', error.headers);
    console.log('Response Err Code:', error.code);
    console.log('Response Err Msg:', error.message);
  } else {
    console.log('unexpected exception, message: ', error);
  }
}

async function main() {
  try {
    const bucketName = 'node-sdk-test-bucket';

    // 删除桶中所有对象
    for (let isTruncated = true, keyMarker = '', versionIdMarker = ''; isTruncated; ) {
      const { data } = await client.listObjectVersions({
        maxKeys: 1000,
        bucket: bucketName,
        keyMarker,
        versionIdMarker,
      });

      // 删除多版本对象
      for (const object of data.Versions) {
        const { requestId } = await client.deleteObject({
          bucket: bucketName,
          key: object.Key,
          versionId: object.VersionId,
        });
        console.log('deleteObject %s Request ID:', object.Key, requestId);
      }

      // 删除标记信息
      for (const markers of data.DeleteMarkers) {
        const { requestId } = await client.deleteObject({
          bucket: bucketName,
          key: markers.Key,
          versionId: markers.VersionId,
        });
        console.log('deleteObject DeleteMarker %s Request ID:', markers.Key, requestId);
      }
      isTruncated = data.IsTruncated;
      keyMarker = data.NextKeyMarker;
      versionIdMarker = data.NextVersionIdMarker;
    }

    // 删除所有未合并的对象
    for (let isTruncated = true, keyMarker = '', uploadIdMarker = ''; isTruncated; ) {
      const { data } = await client.listMultipartUploads({
        bucket: bucketName,
        maxUploads: 1000,
        keyMarker,
        uploadIdMarker,
      });
      for (const upload of data.Uploads) {
        const { requestId } = await client.abortMultipartUpload({
          bucket: bucketName,
          key: upload.Key,
          uploadId: upload.UploadId,
        });
        console.log('abortMultipartUpload uploadId: %s, requestId: %s', upload.UploadId, requestId);
      }
      isTruncated = data.IsTruncated;
      keyMarker = data.NextKeyMarker;
      uploadIdMarker = data.NextUploadIdMarker;
    }
  } catch (error) {
    handleError(error);
  }
}

main();