使用 Node.js
支援將於 2027 年 8 月 6 日結束。 IBM Cloud® Object Storage (COS)SDK v1 將於 2027 年 8 月 6 日停止支援。 此日期之後,該產品將不再獲得更新、安全性修補程式或新版本。 我們建議您遷移至 IBM Cloud Object Storage SDK Node.js v2,該服務不僅提供更佳的效能、更強大的安全性與現代化的 API,還可持續獲得 IBM 的技術支援。
IBM Cloud® Object Storage SDK for Node.js 提供可充分利用 IBM Cloud Object Storage 的現代功能。
安裝 SDK
Node.js 是建置 Web 應用程式 及為一般使用者自訂 Object Storage 實例的絕佳方式。 安裝 Object Storage SDK for Node.js 的偏好方式是使用
Node.js的 npm 套件管理程式。在指令行中鍵入下列指令:
npm install ibm-cos-sdk
若要直接下載 SDK,原始碼是在 GitHub上管理。
有關各個方法和類別的更多詳細資訊,請參閱 SDK 的 API 文件。
開始使用
最低需求
若要執行 SDK,您需要 Node 4.x+。
建立用戶端及讀取認證
為了連接至 COS,會藉由提供認證資訊(API 金鑰、服務實例 ID 及 IBM Authentication Endpoint),來建立及配置用戶端。 這些值也可以自動從 credentials 檔案或環境變數中取得。
產生服務認證後,會將產生的 JSON 文件儲存為 ~/.bluemix/cos_credentials。 除非在建立用戶端期間,明確地設定其他認證,否則 SDK 將自動從此檔案讀取認證。 如果 cos_credentials 檔案包含 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);
金鑰值
<endpoint>- 您的雲端物件儲存服務的公開端點(可從 IBM Cloud 儀表板取得)。 如需端點的相關資訊,請參閱端點及儲存空間位置。<api-key>- 建立服務憑證時所產生的 API 金鑰(建立與刪除範例需具備寫入權限)<resource-instance-id>- 您的雲端物件儲存資源 ID(可透過 IBM Cloud CLI 或 IBM Cloud 控制台取得 )
建立儲存區
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();
建立一個啟用物件鎖定功能的新 COS 儲存桶(即將推出)
function createBucket(bucketName) {
console.log(`Creating new bucket: ${bucketName}`);
return cos.createBucket({
Bucket: bucketName,
ObjectLockEnabledForBucket: true,
CreateBucketConfiguration: {
LocationConstraint: ''
},
}).promise()
.then((() => {
console.log(`Bucket: ${bucketName} created!`);
}))
.catch((e) => {
console.error(`ERROR: ${e.code} - ${e.message}\n`);
});
}
在 COS 儲存桶上啟用物件鎖定設定與合規模式(即將推出)
function putObjectLockConfigurationOnBucket(bucketName) {
console.log(`Putting Objectlock Configuration on : ${bucketName}`);
// Putting objectlock configuration
var defaultRetention = {Mode: 'COMPLIANCE', Days: 1}
var objectLockRule = {DefaultRetention : defaultRetention}
var param = {ObjectLockEnabled: 'Enabled', Rule: objectLockRule}
return cos.putObjectLockConfiguration({
Bucket: bucketName,
ObjectLockConfiguration: param
}).promise()
.then(() => {
console.log(`Object lock Configurtion added!!`);
logDone();
})
.catch(logError);
}
在 COS 儲存桶上啟用物件鎖定設定與治理模式(即將推出)
function putObjectLockConfigurationWithGovernanceModeOnBucket(bucketName) {
console.log(`Putting Objectlock Configuration on : ${bucketName}`);
// Putting objectlock configuration
var defaultRetention = {Mode: 'GOVERNANCE', Days: 1}
var objectLockRule = {DefaultRetention : defaultRetention}
var param = {ObjectLockEnabled: 'Enabled', Rule: objectLockRule}
return cos.putObjectLockConfiguration({
Bucket: bucketName,
ObjectLockConfiguration: param
}).promise()
.then(() => {
console.log(`Object lock Configurtion with Governance mode added!!`);
logDone();
})
.catch(logError);
}
取得 COS 儲存桶的物件鎖定設定(即將推出)
function getObjectLockConfigurationonBucket(bucketName) {
console.log(`Getting Objectlock Configuration for : ${bucketName}`);
// Getting objectlock configuration
return cos.getObjectLockConfiguration({
Bucket: bucketName,
}).promise()
.then((data) => {
console.log(`objectlock configuration`);
console.log( JSON.stringify(data.ObjectLockConfiguration, null, " ") );
logDone();
})
.catch(logError);
}
上傳具有治理模式的物件至 COS 儲存桶(即將推出)
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!`);
logDone();
})
.catch(logError);
}
在物件上啟用物件鎖存留與合規模式(即將推出)
function putObjectLockRetention(bucketName,keyName) {
console.log(`Putting Objectlock Retention on : ${keyName}`);
var inFiveSecond = (new Date(Date.now() + (1000 * 5)))
var rule = {Mode: 'COMPLIANCE', RetainUntilDate: inFiveSecond}
// Putting objectlock retention
return cos.putObjectRetention({
Bucket: bucketName,
Key: keyName,
Retention: rule
}).promise()
.then(() => {
console.log(`Object lock Retention added!!`);
logDone();
})
.catch(logError);
}
在物件上啟用物件鎖保留與治理模式(即將推出)
function putObjectLockRetentionWithGovernanceMode(bucketName,keyName) {
console.log(`Putting Objectlock Retention on : ${keyName}`);
var inFiveSecond = (new Date(Date.now() + (1000 * 5)))
var rule = {Mode: 'GOVERNANCE', RetainUntilDate: inFiveSecond}
// Putting objectlock retention
return cos.putObjectRetention({
Bucket: bucketName,
Key: keyName,
Retention: rule
}).promise()
.then(() => {
console.log(`Object lock Retention with governance mode added!!`);
logDone();
})
.catch(logError);
}
取得物件鎖保留(即將推出)
function getObjectLockRetention(bucketName,keyName) {
console.log(`Getting Objectlock Retention for : ${keyName}`);
// Getting objectlock retention
return cos.getObjectRetention({
Bucket: bucketName,
Key: keyName
}).promise()
.then((data) => {
console.log(`Objectlock retention for : ${keyName} `);
console.log( JSON.stringify(data.Retention, null, " ") );
logDone();
})
.catch(logError);
}
設定物件鎖定法律保留狀態(即將推出)
function putObjectLocklegalHold(bucketName,keyName) {
console.log(`Putting Objectlock legal-hold status ON for : ${keyName}`);
// Putting objectlock legal-hold status
return cos.putObjectlegalHold({
Bucket: bucketName,
Key: keyName,
LegalHold: {Status: 'ON'}
}).promise()
.then(() => {
console.log(`Object lock legal-hold added!!`);
logDone();
})
.catch(logError);
}
取得物件鎖定法律保留(即將推出)
function getObjectLocklegalHold(bucketName,keyName) {
console.log(`Getting Objectlock legal-hold for : ${keyName}`);
// Getting objectlock legal-hold
return cos.getObjectlegal-hold({
Bucket: bucketName,
Key: keyName
}).promise()
.then((data) => {
console.log(`Objectlock legal-hold for : ${keyName} `);
console.log( JSON.stringify(data.legal-hold, null, " ") );
logDone();
})
.catch(logError);
}
使用繞過治理刪除具有物件鎖治理模式的物件(即將推出)
function deleteObjectWithGovernanceMode(bucketName,keyName) {
console.log(`Deleting an object with bypass governance : ${keyName}`);
// Deleting an object with bypass governance
return cos.deleteObject({
Bucket: bucketName,
Key: objectKey,
BypassGovernanceRetention: true,
}).promise()
.then(() => {
console.log("Object deleted");
})
.catch(err => {
console.error("Error deleting object:", err);
});
}
使用 Key Protect
Key Protect 可新增至儲存空間儲存區,以管理加密金鑰。 在 IBM COS 中所有資料都已加密,但 Key Protect 提供了一項服務,來使用集中化服務產生、替換及控制對加密金鑰的存取權。
開始之前
若要建立一個啟用 Key-Protect 功能的儲存桶,需具備以下項目:
擷取根金鑰 CRN
- 擷取 Key Protect 服務的實例 ID
- 使用 Key Protect API 來擷取所有可用金鑰
- 您可以使用
curl指令或 API REST 用戶端(例如 Postman)來存取 Key Protect API。
- 您可以使用
- 擷取您將使用來在儲存區上啟用 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 參照
使用保存特性
Archive Tier 允許使用者保存舊資料,並減少它們的儲存空間成本。 保存原則(也稱為生命週期配置)是針對儲存區而建立,適用於在原則建立之後新增至儲存區的任何物件。
檢視儲存區的生命週期配置
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 參照
更新 meta 資料
有兩種方式可更新現有物件上的 meta 資料:
- 具有新 meta 資料及原始物件內容的
PUT要求 - 使用新 meta 資料來執行
COPY要求,並指定原始物件作為副本來源
使用 PUT 更新 meta 資料
注意: 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 更新 meta 資料
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`);
});
}
使用 Immutable Object Storage
將保護配置新增至現有儲存區
在保護期間過期,並移除物件上的所有合法保留之前,無法刪除寫入受保護儲存區的物件。 除非在物件建立時提供物件特定值,否則會將儲存區的預設保留值提供給物件。 不再保留的受保護儲存區物件(保留期間已過期,而物件沒有任何合法保留),在被改寫時會再次保留。 新的保留期間可以提供為物件改寫要求的一部分,否則會將儲存區的預設保留時間提供給物件。
保留期間設定值 MinimumRetention、DefaultRetention 及 MaximumRetention 的最小和最大支援值分別是 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 |
字串 | 要套用至物件的單一合法保留。 合法保留是 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`);
});
}
新增或移除受保護物件的合法保留
物件可支援 100 個合法保留:
- 合法保留 ID 是長度上限為 64 個字元的字串,且長度下限為 1 個字元。 有效字元包括字母、數字、
!、_、.、*、(、)、-以及'。 - 如果給定合法保留新增數超過物件上的 100 個合法保留總數,則不會新增合法保留,將會傳回
400錯誤。 - 如果 ID 太長,將不會新增到物件中,且會傳回
400錯誤。 - 如果 ID 包含無效的字元,則不會將它新增至物件,且會傳回
400錯誤。 - 如果某個 ID 已在物件上使用,則不會修改現有合法保留,且回應會指出 ID 已在使用中,並且有
409錯誤。 - 如果物件沒有保留期間 meta 資料,則會傳回
400錯誤,且不容許新增或移除合法保留。
正在新增或移除合法保留的使用者必須具有此儲存區的 Manager 許可權。
function addLegalHoldToObject(bucketName, objectName, legalHoldId) {
console.log(`Adding legal hold ${legalHoldId} to object ${objectName} in bucket ${bucketName}`);
return cos.client.addLegalHold({
Bucket: bucketName,
Key: objectId,
RetentionLegalHoldId: legalHoldId
}).promise()
.then(() => {
console.log(`Legal hold ${legalHoldId} added to object ${objectName} in bucket ${bucketName}!`);
})
.catch((e) => {
console.log(`ERROR: ${e.code} - ${e.message}\n`);
});
}
function deleteLegalHoldFromObject(bucketName, objectName, legalHoldId) {
console.log(`Deleting legal hold ${legalHoldId} from object ${objectName} in bucket ${bucketName}`);
return cos.client.deleteLegalHold({
Bucket: bucketName,
Key: objectId,
RetentionLegalHoldId: legalHoldId
}).promise()
.then(() => {
console.log(`Legal hold ${legalHoldId} deleted from object ${objectName} in bucket ${bucketName}!`);
})
.catch((e) => {
console.log(`ERROR: ${e.code} - ${e.message}\n`);
});
}
延長受保護物件的保留期間
只能延長物件的保留期間。 不能從目前配置的值縮短。
保留擴充值以三種方式之一來設定:
- 現行值再加上時間(
Additional-Retention-Period或類似方法) - 新擴充期間(以秒為單位)(
Extend-Retention-From-Current-Time或類似方法) - 物件的新保留到期日(
New-Retention-Expiration-Date或類似方法)
儲存在物件 meta 資料中的現行保留期間,會增加給定的額外時間,或以新值取代,視 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`);
});
}
列出受保護物件的合法保留
此作業傳回:
- 物件建立日期
- 物件保留期間(秒)
- 根據期間和建立日期計算的保留到期日
- 合法保留的清單
- 合法保留 ID
- 套用合法保留時的時間戳記
如果物件沒有任何合法保留,則會傳回空的 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`);
});
}
建立代管的靜態網站
這項作業需要許可權,因為通常只允許儲存區擁有者配置儲存區來管理靜態網站。 這些參數決定網站訪客的預設字尾,以及選用的錯誤文件。
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上的原始碼。