IBM Cloud Docs
使用 Node.js

使用 Node.js

IBM Cloud® Object Storage SDK for Node.js 提供了可充分利用 IBM Cloud Object Storage 的现代功能。

安装 SDK

Node.js 是构建 Web 应用程序 以及为最终用户定制 Object Storage 实例的绝佳方法。 安装 Object Storage SDK for Node.js 的首选方法是使用 npm 软件包管理器 for Node.js。在命令行中输入以下命令:

npm install ibm-cos-sdk

要直接下载 SDK,源代码在 GitHub上托管。

有关各个方法和类的更多详情,请参阅 SDK 的 API 文档

入门

最低需求

要运行 SDK,您需要 Node 4.x+

创建客户机和获取凭证

为了连接到 COS,将通过提供凭证信息(API 密钥、服务实例标识和 IBM 认证端点)来创建和配置客户机。 这些值还可以自动从凭证文件或环境变量中获取。

生成服务凭证后,生成的 JSON 文档可以保存到 ~/.bluemix/cos_credentials。 除非在客户机创建期间显式设置了其他凭证,否则 SDK 会自动从此文件中获取凭证。 如果 cos_credentials 文件包含 HMAC 密钥,那么客户机会使用签名进行认证;如果不包含 HMAC 密钥,客户机将使用提供的 API 密钥通过不记名令牌进行认证。

default 部分的标题指定用于凭证的缺省概要文件和关联的值。 可以在同一共享配置文件中创建更多概要文件,每个概要文件包含自己的凭证信息。 以下示例显示了具有缺省概要文件的配置文件:

[default]
ibm_api_key_id = <DEFAULT_IBM_API_KEY>
ibm_service_instance_id = <DEFAULT_IBM_SERVICE_INSTANCE_ID>
ibm_auth_endpoint = <DEFAULT_IBM_AUTH_ENDPOINT>

如果是从 AWS S3 进行迁移,那么还可以从 ~/.aws/credentials 中获取以下格式的凭证数据:

aws_access_key_id = <DEFAULT_ACCESS_KEY_ID>
aws_secret_access_key = <DEFAULT_SECRET_ACCESS_KEY>

如果 ~/.bluemix/cos_credentials~/.aws/credentials 同时存在,那么 cos_credentials 优先。

代码示例

在您的代码中,必须除去此处作为插图提供的尖括号或任何其他多余字符。

Node.js入门-安装后-通常涉及配置和调用,如 此示例中的 Nodejs.org所示。 我们将遵循类似的模型

初始化配置

const IBM = require('ibm-cos-sdk');

var config = {
    endpoint: '<endpoint>',
    apiKeyId: '<api-key>',
    serviceInstanceId: '<resource-instance-id>',
    signatureVersion: 'iam',
};

var cos = new IBM.S3(config);

键值

创建存储区

LocationConstraint 的有效配置代码列表可参考《 存储类别指南 》。

function createBucket(bucketName) {
    console.log(`Creating new bucket: ${bucketName}`);
    return cos.createBucket({
        Bucket: bucketName,
        CreateBucketConfiguration: {
          LocationConstraint: 'us-standard'
        },
    }).promise()
    .then((() => {
        console.log(`Bucket: ${bucketName} created!`);
    }))
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

创建文本对象

function createTextFile(bucketName, itemName, fileText) {
    console.log(`Creating new item: ${itemName}`);
    return cos.putObject({
        Bucket: bucketName,
        Key: itemName,
        Body: fileText
    }).promise()
    .then(() => {
        console.log(`Item: ${itemName} created!`);
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

列出存储区

function getBuckets() {
    console.log('Retrieving list of buckets');
    return cos.listBuckets()
    .promise()
    .then((data) => {
        if (data.Buckets != null) {
            for (var i = 0; i < data.Buckets.length; i++) {
                console.log(`Bucket Name: ${data.Buckets[i].Name}`);
            }
        }
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

列出存储区中的项

function getBucketContents(bucketName) {
    console.log(`Retrieving bucket contents from: ${bucketName}`);
    return cos.listObjects(
        {Bucket: bucketName},
    ).promise()
    .then((data) => {
        if (data != null && data.Contents != null) {
            for (var i = 0; i < data.Contents.length; i++) {
                var itemKey = data.Contents[i].Key;
                var itemSize = data.Contents[i].Size;
                console.log(`Item: ${itemKey} (${itemSize} bytes).`)
            }
        }
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

获取特定项的文件内容

function getItem(bucketName, itemName) {
    console.log(`Retrieving item from bucket: ${bucketName}, key: ${itemName}`);
    return cos.getObject({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then((data) => {
        if (data != null) {
            console.log('File Contents: ' + Buffer.from(data.Body).toString());
        }
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

从存储区中删除一个项

function deleteItem(bucketName, itemName) {
    console.log(`Deleting item: ${itemName}`);
    return cos.deleteObject({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then(() =>{
        console.log(`Item: ${itemName} deleted!`);
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

从存储区中删除多个项

删除请求最多可包含 1000 个要删除的键。 虽然批量删除对象对于减少每个请求的开销非常有用,但在删除大量键时应谨慎,请求可能需要一些时间才能完成。 此外,还要考虑对象的大小,以确保合适的性能。

function deleteItems(bucketName) {
    var deleteRequest = {
        "Objects": [
            { "Key": "deletetest/testfile1.txt" },
            { "Key": "deletetest/testfile2.txt" },
            { "Key": "deletetest/testfile3.txt" },
            { "Key": "deletetest/testfile4.txt" },
            { "Key": "deletetest/testfile5.txt" }
        ]
    }
    return cos.deleteObjects({
        Bucket: bucketName,
        Delete: deleteRequest
    }).promise()
    .then((data) => {
        console.log(`Deleted items for ${bucketName}`);
        console.log(data.Deleted);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

删除存储区

function deleteBucket(bucketName) {
    console.log(`Deleting bucket: ${bucketName}`);
    return cos.deleteBucket({
        Bucket: bucketName
    }).promise()
    .then(() => {
        console.log(`Bucket: ${bucketName} deleted!`);
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

执行分块上传

function multiPartUpload(bucketName, itemName, filePath) {
    var uploadID = null;

    if (!fs.existsSync(filePath)) {
        log.error(new Error(`The file \'${filePath}\' does not exist or is not accessible.`));
        return;
    }

    console.log(`Starting multi-part upload for ${itemName} to bucket: ${bucketName}`);
    return cos.createMultipartUpload({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then((data) => {
        uploadID = data.UploadId;

        //begin the file upload
        fs.readFile(filePath, (e, fileData) => {
            //min 5MB part
            var partSize = 1024 * 1024 * 5;
            var partCount = Math.ceil(fileData.length / partSize);

            async.timesSeries(partCount, (partNum, next) => {
                var start = partNum * partSize;
                var end = Math.min(start + partSize, fileData.length);

                partNum++;

                console.log(`Uploading to ${itemName} (part ${partNum} of ${partCount})`);

                cos.uploadPart({
                    Body: fileData.slice(start, end),
                    Bucket: bucketName,
                    Key: itemName,
                    PartNumber: partNum,
                    UploadId: uploadID
                }).promise()
                .then((data) => {
                    next(e, {ETag: data.ETag, PartNumber: partNum});
                })
                .catch((e) => {
                    cancelMultiPartUpload(bucketName, itemName, uploadID);
                    console.error(`ERROR: ${e.code} - ${e.message}\n`);
                });
            }, (e, dataPacks) => {
                cos.completeMultipartUpload({
                    Bucket: bucketName,
                    Key: itemName,
                    MultipartUpload: {
                        Parts: dataPacks
                    },
                    UploadId: uploadID
                }).promise()
                .then(console.log(`Upload of all ${partCount} parts of ${itemName} successful.`))
                .catch((e) => {
                    cancelMultiPartUpload(bucketName, itemName, uploadID);
                    console.error(`ERROR: ${e.code} - ${e.message}\n`);
                });
            });
        });
    })
    .catch((e) => {
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

function cancelMultiPartUpload(bucketName, itemName, uploadID) {
    return cos.abortMultipartUpload({
        Bucket: bucketName,
        Key: itemName,
        UploadId: uploadID
    }).promise()
    .then(() => {
        console.log(`Multi-part upload aborted for ${itemName}`);
    })
    .catch((e)=>{
        console.error(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

创建备份策略

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config values
const apiKey = '<API_KEY>';
const sourceBucketName = '< SOURCE_BUCKET_NAME>';
const backupVaultCrn = '<BACKUP_VAULT_CRN>';
const policyName = '<BACKUP_POLICY_NAME>';

async function  createBackupPolicy () {
  try {
    // Authenticator and client setup
    const authenticator = new IamAuthenticator({ apikey: apiKey });
    const rcClient = new ResourceConfigurationV1({ authenticator });

    // Create backup policy
    const response = await rcClient.createBackupPolicy({
      bucket: sourceBucketName,
      policyName: policyName,
      targetBackupVaultCrn: backupVaultCrn,
      backupType: “continuous”,
      initialRetention: {delete_after_days:1},
    });

    console.log('Backup  policy created successfully: ‘, response.result);

  } catch (err) {
    console.error('Error:', err);
  }
}
// Run the function
createBackupPolicy ();

列出备份策略

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const sourceBucketName = '<SOURCE_BUCKET_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function listBackupPolicies() {
  try {

    // List all backup policies
    const listResponse = await rcClient.listBackupPolicies({
      bucket: sourceBucketName,
    });

    console.log('\n List of backup policies:');
    const policies = listResponse.result.backup_policies || [];
    policies.forEach(policy => console.log(policy));

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
listBackupPolicies();

制定备份政策

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const sourceBucketName = '<SOURCE_BUCKET_NAME>';
const policyId = '<POLICY_ID>'; // Policy ID to retrieve backup Policy

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function fetchBackupPolicy () {
  try {
    // Fetch backup policy
    const getResponse = await rcClient.getBackupPolicy({
      bucket: sourceBucketName,
      policyId: policyId,
    });
    console.log('\nFetched Backup Policy Details:');
    console.log(getResponse.result);

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
fetchBackupPolicy ();

删除备份策略

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const sourceBucketName = '<SOURCE_BUCKET_NAME>';
const policyId = '<POLICY_ID_TO_DELETE>'; // Policy ID of the policy to be deleted

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });
async function deleteBackupPolicy() {
try {
    // Delete backup policy
    await rcClient.deleteBackupPolicy({
      bucket: sourceBucketName,
      policyId: policyId,
    });

    console.log(`Backup policy '${policyId}' deleted successfully.`);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
deleteBackupPolicy ();

创建备份库

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const serviceInstanceId = '<SERVICE_INSTANCE_ID>';
const region = '<REGION>';
const backupVaultName = <BACKUP_VAULT_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function createBackupVault() {
  try {

    const createResponse = await rcClient.createBackupVault({
      serviceInstanceId: serviceInstanceId,
      backupVaultName: backupVaultName,
      region: region,
    });

    console.log('Backup vault created:');
    console.log(createResponse.result);
  } catch (error) {
    console.error('Error creating backup vault:', error);
  }
}

// Run the function
createBackupVault();

列表备份库

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const serviceInstanceId = '<SERVICE_INSTANCE_ID>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function listBackupVaults() {
  try {
    // List backup vaults
    const listResponse = await rcClient.listBackupVaults({
      serviceInstanceId: serviceInstanceId,
    });

    console.log('List of backup vaults:');
    console.log(listResponse.result);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
listBackupVaults ();

获取备份库

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>'; // Name of the backup vault to fetch

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function fetchBackupVault () {
  try {
    // Get backup vault
    const getResponse = await rcClient.getBackupVault({
      backupVaultName: backupVaultName,
    });

    console.log('Backup vault details:');
    console.log(getResponse.result);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
fetchBackupVault ();

更新备份库

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1');

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>'; // Keep consistent for create + update

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function updateBackupVault() {
  try {
    // Update backup vault to disable tracking and monitoring
    const patch = {
      activity_tracking: {
        management_events: false,
      },
      metrics_monitoring: {
        usage_metrics_enabled: false,
      },
    };

    const updateResponse = await rcClient.updateBackupVault({
      backupVaultName: backupVaultName,
      backupVaultPatch: patch,
    });

    console.log(`Backup vault updated. Status code: ${updateResponse.status}`);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
updateBackupVault ();

删除备份库

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function deleteBackupVault() {
  try {
    // Delete the backup vault
    await rcClient.deleteBackupVault({
      backupVaultName: backupVaultName,
    });

    console.log(`Backup vault '${backupVaultName}' deleted successfully.`);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
deleteBackupVault();

列表恢复范围

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function listRecoveryRanges() {
  try {
    // List recovery ranges
    const recoveryRangesResponse = await rcClient.listRecoveryRanges({
      backupVaultName: backupVaultName,
    });

    console.log('Recovery Ranges:');
    console.log(recoveryRangesResponse.result);
  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
listRecoveryRanges();

获取恢复范围

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const recoveryRangeId = '<RECOVERY_RANGE_ID>';
const backupVaultName = '<BACKUP_VAULT_NAME>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function fetchRecoveryRangeInfo() {

try {
    // Fetch details of the recovery range
    const recoveryRangeId = createResponse.result.recovery_range_id;  // Assuming the recovery range info is part of the response
    const getRecoveryRangeResponse = await rcClient.getSourceResourceRecoveryRange({
      backupVaultName: backupVaultName,
      recoveryRangeId: recoveryRangeId,
    });

    console.log('Recovery Range Details:');
    console.log(getRecoveryRangeResponse.result);
  } catch (error) {
    console.error('Error:', error);
  }
}
// Run the function
fetchRecoveryRangeInfo();

更新恢复范围

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1');

// Config
const apiKey = '<API_KEY>';
const backupVaultCrn = '<BACKUP_VAULT_CRN>';
const recoveryRangeId = '<RECOVERY_RANGE_ID>';
const policyId = '<POLICY_ID>';

// Setup authenticator and client
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });

async function patchRecoveryRange() {
  try {
    // Patch the recovery range retention
    const patchResponse = await rcClient.patchSourceResourceRecoveryRange({
      backupVaultName: backupVaultName,
      recoveryRangeId: recoveryRangeId,
      retention: {
          delete_after_days: 99
        }
    });

    console.log('Recovery range updated successfully:');
    console.log(patchResponse.result);

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
patchRecoveryRange ();

启动还原

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Configuration
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';
const recoveryRangeId = '<RECOVERY_RANGE_ID>';
const targetBucketCrn = '<TARGET_BUCKET_CRN>';
const restorePointInTime = '<RESTORE_POINT_TIME>';
const endpoint = '<COS_ENDPOINT>';

// Setup authenticator and clients
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });
rcClient.setServiceUrl("SERVICE_URL");

async function initiateRestore () {
  try {
    // Initiate restore
    const createRestoreResponse = await rcClient.createRestore({
      backupVaultName: backupVaultName,
      recoveryRangeId: recoveryRangeId,
      restoreType: 'in_place',
      restorePointInTime: restorePointInTime,
      targetResourceCrn: targetBucketCrn,
    });

    const restoreId = createRestoreResponse.result.restore_id;
    console.log(`Restore initiated with ID: ${restoreId}`);

  } catch (error) {
    console.error('Error:', error);
  }
}

// Run the function
initiateRestore ();

列表恢复

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')

// Config
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';

// Auth & Clients
const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });
rcClient.setServiceUrl("SERVICE_URL");

async function listRestore()  {
  try {
    // List restore operations
    const listRestoreResp = await rcClient.listRestores({
      backupVaultName: backupVaultName
    });

    console.log('Restore operations:', listRestoreResp.result);
  } catch (err) {
    console.error('Error occurred:', err);
  }
};

// Run the function
listRestore();

获取恢复详情

const { IamAuthenticator } = require('ibm-cloud-sdk-core');
const ResourceConfigurationV1 = require('ibm-cos-sdk-config/resource-configuration/v1')
// Configuration
const apiKey = '<API_KEY>';
const backupVaultName = '<BACKUP_VAULT_NAME>';
const restoreId = '<RESTORE_ID>';

const authenticator = new IamAuthenticator({ apikey: apiKey });
const rcClient = new ResourceConfigurationV1({ authenticator });
rcClient.setServiceUrl("SERVICE_URL");

async function getRestore()  {
  try {
    // Get specific restore
    const restoreDetails = await rcClient.getRestore({
      backupVaultName: backupVaultName,
      restoreId: restoreId
    });
    console.log('Restore details:', restoreDetails.result);

  } catch (err) {
    console.error('Error:', err);
  }
}
getRestore();

使用 Key Protect

可以将 Key Protect 添加到存储区,以管理加密密钥。 所有数据都在 IBM COS 中进行加密,但 Key Protect 提供的是使用集中服务来生成和循环加密密钥以及控制加密密钥访问权的服务。

准备工作

要创建一个启用密钥保护的水桶,需要以下项目:

检索根密钥 CRN

  1. 检索 Key Protect 服务的实例标识
  2. 使用 Key Protect API 来检索所有可用密钥
  3. 检索将用于在存储区上启用 Key Protect 的根密钥的 CRN。 CRN 类似于以下内容:

crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234

创建启用了 Key Protect 的存储区

function createBucketKP(bucketName) {
    console.log(`Creating new encrypted bucket: ${bucketName}`);
    return cos.createBucket({
        Bucket: bucketName,
        CreateBucketConfiguration: {
          LocationConstraint: '<bucket-location>'
        },
        IBMSSEKPEncryptionAlgorithm: '<algorithm>',
        IBMSSEKPCustomerRootKeyCrn: '<root-key-crn>'
    }).promise()
    .then((() => {
        console.log(`Bucket: ${bucketName} created!`);
        logDone();
    }))
    .catch(logError);
}

键值

  • <bucket-location>- 水桶的地区或位置( Key Protect 仅适用于某些地区。 确保您的位置与 Key Protect 服务相匹配) LocationConstraint 的有效供应代码列表可在 存储类别指南 中参考。
  • <algorithm>- 新对象添加到数据桶时使用的加密算法(默认为 AES256 )。
  • <root-key-crn>- 从 Key Protect 服务获取的根密钥的 CRN。

SDK 参考

使用归档功能

通过归档层,用户可以归档旧数据并降低其存储成本。 归档策略(也称为生命周期配置)是针对存储区创建的,并应用于创建策略后添加到存储区的任何对象。

查看存储区的生命周期配置

function getLifecycleConfiguration(bucketName) {
    return cos.getBucketLifecycleConfiguration({
        Bucket: bucketName
    }).promise()
    .then((data) => {
        if (data != null) {
            console.log(`Retrieving bucket lifecycle config from: ${bucketName}`);
            console.log(JSON.stringify(data, null, 4));
        }
        else {
            console.log(`No lifecycle configuration for ${bucketName}`);
        }
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

创建生命周期配置

API 参考中提供了有关构造生命周期配置规则的详细信息

function createLifecycleConfiguration(bucketName) {
    //
    var config = {
        Rules: [{
            Status: 'Enabled',
            ID: '<policy-id>',
            Filter: {
                Prefix: ''
            },
            Transitions: [{
                Days: <number-of-days>,
                StorageClass: 'GLACIER'
            }]
        }]
    };

    return cos.putBucketLifecycleConfiguration({
        Bucket: bucketName,
        LifecycleConfiguration: config
    }).promise()
    .then(() => {
        console.log(`Created bucket lifecycle config for: ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

键值

  • <policy-id>- 生命周期策略名称(必须唯一)
  • <number-of-days>- 保存恢复文件的天数

SDK 参考

删除存储区的生命周期配置

function deleteLifecycleConfiguration(bucketName) {
    return cos.deleteBucketLifecycle({
        Bucket: bucketName
    }).promise()
    .then(() => {
        console.log(`Deleted bucket lifecycle config from: ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

临时复原对象

API 参考中提供了有关复原请求参数的详细信息

function restoreItem(bucketName, itemName) {
    var params = {
        Bucket: bucketName,
        Key: itemName,
        RestoreRequest: {
            Days: <number-of-days>,
            GlacierJobParameters: {
                Tier: 'Bulk'
            },
        }
    };

    return cos.restoreObject(params).promise()
    .then(() => {
        console.log(`Restoring item: ${itemName} from bucket: ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

键值

  • <number-of-days>- 保存恢复文件的天数

SDK 参考

查看对象的 HEAD 信息

function getHEADItem(bucketName, itemName) {
    return cos.headObject({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then((data) => {
        console.log(`Retrieving HEAD for item: ${itemName} from bucket: ${bucketName}`);
        console.log(JSON.stringify(data, null, 4));
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

SDK 参考

更新元数据

有两种方法可更新现有对象上的元数据:

  • 对新的元数据和原始对象内容执行 PUT 请求
  • 使用将原始对象指定为复制源的新元数据来执行 COPY 请求

使用 PUT 更新元数据

注意: PUT 请求会覆盖对象的现有内容,因此必须首先下载并重新上传新的元数据。

function updateMetadataPut(bucketName, itemName, metaValue) {
    console.log(`Updating metadata for item: ${itemName}`);

    //retrieve the existing item to reload the contents
    return cos.getObject({
        Bucket: bucketName,
        Key: itemName
    }).promise()
    .then((data) => {
        //set the new metadata
        var newMetadata = {
            newkey: metaValue
        };

        return cos.putObject({
            Bucket: bucketName,
            Key: itemName,
            Body: data.Body,
            Metadata: newMetadata
        }).promise()
        .then(() => {
            console.log(`Updated metadata for item: ${itemName} from bucket: ${bucketName}`);
        })
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

使用 COPY 更新元数据

function updateMetadataCopy(bucketName, itemName, metaValue) {
    console.log(`Updating metadata for item: ${itemName}`);

    //set the copy source to itself
    var copySource = bucketName + '/' + itemName;

    //set the new metadata
    var newMetadata = {
        newkey: metaValue
    };

    return cos.copyObject({
        Bucket: bucketName,
        Key: itemName,
        CopySource: copySource,
        Metadata: newMetadata,
        MetadataDirective: 'REPLACE'
    }).promise()
    .then((data) => {
        console.log(`Updated metadata for item: ${itemName} from bucket: ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

使用不可变对象存储器

向现有存储区添加保护配置

对于写入受保护存储区的对象,在保护时间段到期并且除去了对象上的所有合法保留之前,无法删除这些对象。 除非在创建对象时提供了特定于对象的值,否则将向对象提供存储区的缺省保留时间值。 如果覆盖受保护存储区中不再保留的对象(保留期已到期,并且对象没有任何合法保留),那么会再次保留这些对象。 可以在对象覆盖请求中提供新的保留期,否则会为对象提供存储区的缺省保留时间。

保留期设置 MinimumRetentionDefaultRetentionMaximumRetention 的最小和最大支持值分别为 0 天和 365243 天(1000 年)。

function addProtectionConfigurationToBucket(bucketName) {
    console.log(`Adding protection to bucket ${bucketName}`);
    return cos.putBucketProtectionConfiguration({
        Bucket: bucketName,
        ProtectionConfiguration: {
            'Status': 'Retention',
            'MinimumRetention': {'Days': 10},
            'DefaultRetention': {'Days': 100},
            'MaximumRetention': {'Days': 1000}
        }
    }).promise()
    .then(() => {
        console.log(`Protection added to bucket ${bucketName}!`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

检查存储区上的保护

function getProtectionConfigurationOnBucket(bucketName) {
    console.log(`Retrieve the protection on bucket ${bucketName}`);
    return cos.getBucketProtectionConfiguration({
        Bucket: bucketName
    }).promise()
    .then((data) => {
        console.log(`Configuration on bucket ${bucketName}:`);
        console.log(data);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

上传受保护对象

如果覆盖受保护存储区中不再保留的对象(保留期已到期,并且对象没有任何合法保留),那么会再次保留这些对象。 可以在对象覆盖请求中提供新的保留期,否则会为对象提供存储区的缺省保留时间。

类型 描述
Retention-Period 非负整数(秒) 要在对象上存储的保留期(以秒为单位)。 在保留期中指定的时间长度到期之前,无法覆盖也无法删除对象。 如果同时指定了此字段和 Retention-Expiration-Date,将返回 400 错误。 如果这两个字段均未指定,将使用存储区的 DefaultRetention 时间段。 假定存储区的最短保留期为 0,那么零 (0) 是合法值。
Retention-expiration-date 日期(ISO 8601 格式) 能够合法删除或修改对象的日期。 只能指定此项或指定 Retention-Period 头。 如果同时指定这两项,将返回 400 错误。 如果这两项均未指定,将使用存储区的 DefaultRetention 时间段。
Retention-legal-hold-id string 要应用于对象的单个合法保留。 合法保留是长度为 Y 个字符的字符串。 在除去与对象关联的所有合法保留之前,无法覆盖或删除对象。
function putObjectAddLegalHold(bucketName, objectName, legalHoldId) {
    console.log(`Add legal hold ${legalHoldId} to ${objectName} in bucket ${bucketName} with a putObject operation.`);
    return cos.putObject({
        Bucket: bucketName,
        Key: objectName,
        Body: 'body',
        RetentionLegalHoldId: legalHoldId
    }).promise()
    .then((data) => {
        console.log(`Legal hold ${legalHoldId} added to object ${objectName} in bucket ${bucketName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

function copyProtectedObject(sourceBucketName, sourceObjectName, destinationBucketName, newObjectName, ) {
    console.log(`Copy protected object ${sourceObjectName} from bucket ${sourceBucketName} to ${destinationBucketName}/${newObjectName}.`);
    return cos.copyObject({
        Bucket: destinationBucketName,
        Key: newObjectName,
        CopySource: sourceBucketName + '/' + sourceObjectName,
        RetentionDirective: 'Copy'
    }).promise()
    .then((data) => {
        console.log(`Protected object copied from ${sourceBucketName}/${sourceObjectName} to ${destinationBucketName}/${newObjectName}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

延长受保护对象的保留期

对象的保留期只能延长。 不能在当前配置值的基础上缩短。

保留时间延长值可通过以下三种方式之一进行设置:

  • 在当前值的基础上增加时间(Additional-Retention-Period 或类似方法)
  • 新的延长时间段(以秒为单位)(Extend-Retention-From-Current-Time 或类似方法)
  • 对象的新保留到期日期(New-Retention-Expiration-Date 或类似方法)

根据 extendRetention 请求中设置的参数,对象元数据中存储的当前保留期可通过给定更多时间延长,也可替换为新值。 在所有情况下,都会根据当前保留期来检查延长保留时间参数,并且仅当更新的保留期大于当前保留期时,才会接受延长参数。

如果覆盖受保护存储区中不再保留的对象(保留期已到期,并且对象没有任何合法保留),那么会再次保留这些对象。 可以在对象覆盖请求中提供新的保留期,否则会为对象提供存储区的缺省保留时间。

function extendRetentionPeriodOnObject(bucketName, objectName, additionalSeconds) {
    console.log(`Extend the retention period on ${objectName} in bucket ${bucketName} by ${additionalSeconds} seconds.`);
    return cos.extendObjectRetention({
        Bucket: bucketName,
        Key: objectName,
        AdditionalRetentionPeriod: additionalSeconds
    }).promise()
    .then((data) => {
        console.log(`New retention period on ${objectName} is ${data.RetentionPeriod}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

列出受保护对象上的合法保留

此操作会返回以下内容:

  • 对象创建日期
  • 对象保留期(秒)
  • 根据时间段和创建日期计算的保留到期日期
  • 合法保留的列表
  • 合法保留标识
  • 应用合法保留时的时间戳记

如果对象上没有合法保留,那么会返回空的 LegalHoldSet。 如果在对象上未指定保留期,那么会返回 404 错误。

function listLegalHoldsOnObject(bucketName, objectName) {
    console.log(`List all legal holds on object ${objectName} in bucket ${bucketName}`);
    return cos.listLegalHolds({
        Bucket: bucketName,
        Key: objectId
    }).promise()
    .then((data) => {
        console.log(`Legal holds on bucket ${bucketName}: ${data}`);
    })
    .catch((e) => {
        console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

创建托管静态 Web 站点

此操作需要许可权,因为通常仅允许存储区所有者配置存储区以托管静态 Web 站点。 这些参数确定站点访问者的缺省后缀以及可选错误文档。

var websiteParams = {
  Bucket: "bucketName",
  WebsiteConfiguration: {
    ErrorDocument: {
      Key: "error.html"
    },
    IndexDocument: {
      Suffix: "index.html"
    }
  }
};
function putBucketWebsiteConfiguration(websiteParams) {
  return cos.putBucketWebsite({websiteParams}).promise()
    .then((data) => {
       console.log(`Website configured for ${bucketName}`);
    })
    .catch((e) => {
       console.log(`ERROR: ${e.code} - ${e.message}\n`);
    });
}

后续步骤

可以在 SDK 的 API 文档中找到有关各个方法和类的更多详细信息。 查看 GitHub上的源代码。