Utilizzo di Node.js
Fine del supporto il 6 agosto 2027. Il supporto per l'SDK di COS ( IBM Cloud® Object Storage ) v1 terminerà il 6 agosto 2027. Dopo tale data, non riceverà più aggiornamenti, correzioni di sicurezza né nuove versioni. Consigliamo di passare all'SDK di IBM Cloud Object Storage Node.js v2, che offre prestazioni migliorate, maggiore sicurezza, API moderne e supporto continuo da parte di IBM.
IBM Cloud® Object Storage SDK for Node.js fornisce delle funzionalità moderne che utilizzano in modo ottimale IBM Cloud Object Storage.
Installazione dell'SDK
Node.js è un ottimo modo per creare applicazioni web
e personalizzare la tua istanza di Object Storage per i tuoi utenti finali. Il modo preferito per installare l'SDK Object Storage SDK for Node.js è utilizzare il gestore del pacchetto npm per Node.js. Immettere il seguente comando in una riga comandi:
npm install ibm-cos-sdk
Per scaricare direttamente l'SDK, il codice sorgente è ospitato in GitHub.
Maggiori dettagli sui singoli metodi e sulle singole classi sono disponibili nella documentazione API dell'SDK.
Guida introduttiva
Requisiti minimi
Per eseguire l'SDK, hai bisogno di Node 4.x+.
Creazione di un client e derivazione delle credenziali
Per la connessione a COS, viene creato e configurato un client fornendo le informazioni sulle credenziali (chiave API, ID istanza del servizio ed endpoint di autenticazione IBM). Questi valori possono anche essere derivati automaticamente da un file di credenziali o dalle variabili di ambiente.
Dopo aver generato una credenziale del servizio, il documento JSON risultante può essere salvato in ~/.bluemix/cos_credentials. L'SDK deriverà
automaticamente le credenziali da questo file a meno che non vengano esplicitamente impostate altre credenziali durante la creazione del client. Se il file cos_credentials contiene le chiavi HMAC, il client esegue l'autenticazione
con una firma, altrimenti utilizza la chiave API fornita con un token di connessione.
L'intestazione della sezione default specifica un profilo predefinito e i valori associati alle credenziali. Puoi creare più profili nello stesso file di configurazione, ognuno con le proprie informazioni sulle credenziali. Il
seguente esempio mostra un file di configurazione con il profilo predefinito:
[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>
Se si esegue la migrazione da AWS S3, puoi anche derivare i dati delle credenziali da ~/.aws/credentials nel formato:
aws_access_key_id = <DEFAULT_ACCESS_KEY_ID>
aws_secret_access_key = <DEFAULT_SECRET_ACCESS_KEY>
Se esistono ~/.bluemix/cos_credentials e ~/.aws/credentials, cos_credentials ha la precedenza.
Esempi di codici
Nel codice, è necessario rimuovere le parentesi angolari o qualsiasi altro carattere in eccesso fornito qui come illustrazione.
Per iniziare a utilizzare Node.js- una volta installato - di solito comporta la configurazione e il richiamo, come in questo esempio da Nodejs.org. Seguiremo un modello simile
Inizializzazione della configurazione
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);
Valori chiave
<endpoint>- endpoint pubblico per il tuo sistema di archiviazione oggetti nel cloud (disponibile dalla dashboard di IBM Cloud ). Per ulteriori informazioni sugli endpoint, vedi Endpoint e ubicazioni di archiviazione.<api-key>- Chiave API generata durante la creazione delle credenziali del servizio (per gli esempi relativi alla creazione e all'eliminazione è necessario l'accesso in scrittura)<resource-instance-id>- ID della risorsa per il tuo servizio di archiviazione oggetti nel cloud (disponibile tramite la CLI di IBM Cloud o la dashboard di IBM Cloud )
Creazione di un bucket
È possibile che si faccia riferimento a un elenco di codici di provisioning validi per LocationConstraint nella guida alle classi di archiviazione.
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`);
});
}
Riferimenti SDK
Creazione di un oggetto di testo
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`);
});
}
Riferimenti SDK
Elenca i bucket
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`);
});
}
Riferimenti SDK
Elenca gli elementi in un bucket
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`);
});
}
Riferimenti SDK
Ottieni il contenuto del file di uno specifico elemento
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`);
});
}
Riferimenti SDK
Elimina un elemento da un bucket
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`);
});
}
Riferimenti SDK
Elimina più elementi da un bucket
La richiesta di eliminazione può contenere un massimo di 1000 chiavi che vuoi eliminare. Se da una parte eliminare gli oggetti in batch è molto utile per ridurre il sovraccarico per ogni richiesta, fai attenzione che quando elimini molte chiavi, la richiesta potrebbe richiedere alcuni minuti per il completamento. Inoltre, occorre tenere conto delle dimensioni degli oggetti per garantire prestazioni adeguate.
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`);
});
}
Riferimenti SDK
Elimina un bucket
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`);
});
}
Riferimenti SDK
Esegui un caricamento in più parti
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`);
});
}
Riferimenti SDK
Creazione di un criterio di backup
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 ();
Elencare un criterio di backup
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();
Ottenere una politica di backup
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 ();
Eliminare un criterio di backup
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 ();
Creazione di un vault di backup
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();
Elenco delle camere blindate di backup
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 ();
Ottenere i vault di backup
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 ();
Aggiornare i vault di backup
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 ();
Eliminare un vault di backup
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();
Elenco Gamme di recupero
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();
Ottenere l'intervallo di recupero
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();
Aggiornamento dell'intervallo di recupero
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 ();
Avvio di un ripristino
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 ();
Ripristino dell'elenco
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();
Ottenere i dettagli del ripristino
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();
Crea un nuovo bucket COS con blocco oggetti abilitato (Prossimamente disponibile)
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`);
});
}
Imposta la configurazione del blocco oggetti con modalità di conformità sul bucket COS (Prossimamente disponibile)
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);
}
Imposta la configurazione del blocco degli oggetti con modalità di governance sul bucket COS (Prossimamente disponibile)
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);
}
Ottieni la configurazione del blocco degli oggetti sul bucket COS (Prossimamente disponibile)
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);
}
Carica un oggetto con modalità di governance nel bucket COS (Prossimamente disponibile)
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);
}
Attiva la conservazione del blocco oggetto con modalità di conformità sull'oggetto (Prossimamente disponibile)
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);
}
Attiva la conservazione del blocco degli oggetti con modalità di governance sull'oggetto (Prossimamente disponibile)
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);
}
Ottieni la conservazione del blocco degli oggetti (Prossimamente)
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);
}
Applicare il blocco legale all'oggetto (Prossimamente)
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);
}
Ottieni il blocco legale dell'oggetto (Prossimamente disponibile)
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);
}
Eliminazione di un oggetto con modalità di governance con blocco oggetti utilizzando la governance di bypass (Prossimamente disponibile)
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);
});
}
Utilizzo di Key Protect
Key Protect può essere aggiunto a un bucket di archiviazione per gestire le chiavi di crittografia. Tutti i dati vengono crittografati in IBM COS ma Key Protect fornisce un servizio per generare, ruotare e controllare l'accesso alle chiavi di crittografia utilizzando un servizio centralizzato.
Prima di cominciare
Per creare un bucket con Key-Protect abilitato sono necessari i seguenti elementi:
- Un servizio Key Protect di cui è stato eseguito il provisioning
- Una chiave root disponibile (generata o importata)
Richiamo del CRN di chiave root
- Richiama l'ID istanza per il tuo servizio Key Protect
- Utilizza l'API Key Protect per richiamare tutte le tue chiavi disponibili
- Puoi utilizzare i comandi
curlo un client REST API come Postman per accedere all'API Key Protect.
- Puoi utilizzare i comandi
- Richiama il CRN della chiave root che utilizzerai per abilitare Key Protect sul tuo bucket. Il CRN sarà simile al seguente:
crn:v1:bluemix:public:kms:us-south:a/3d624cd74a0dea86ed8efe3101341742:90b6a1db-0fe1-4fe9-b91e-962c327df531:key:0bg3e33e-a866-50f2-b715-5cba2bc93234
Creazione di un bucket con Key Protect abilitato
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);
}
Valori chiave
<bucket-location>- Regione o ubicazione del bucket ( Key Protect: disponibile solo in determinate regioni. Assicurati che la tua ubicazione corrisponda al servizio Key Protect). È possibile che si faccia riferimento a un elenco di codici di provisioning validi perLocationConstraintnella guida alle classi di archiviazione.<algorithm>- L'algoritmo di crittografia utilizzato per i nuovi oggetti aggiunti al bucket (l'impostazione predefinita è " AES256 ").<root-key-crn>- CRN della chiave principale ottenuta dal servizio Key Protect.
Riferimenti SDK
Utilizzo della funzione di archiviazione
Il livello di archiviazione consente agli utenti di archiviare i dati obsoleti e ridurre i loro costi di archiviazione. Le politiche di archiviazione (note anche come Configurazioni del ciclo di vita) sono create per i bucket e si applicano a tutti gli oggetti aggiunti al bucket dopo la creazione della politica.
Visualizza la configurazione del ciclo di vita di un bucket
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`);
});
}
Riferimenti SDK
Crea una configurazione del ciclo di vita
Informazioni dettagliate su come strutturare le regole della configurazione del ciclo di vita sono disponibili nella Guida di riferimento 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`);
});
}
Valori chiave
<policy-id>- Nome della politica relativa al ciclo di vita (deve essere univoco)<number-of-days>- Numero di giorni per cui conservare il file ripristinato
Riferimenti SDK
Elimina la configurazione del ciclo di vita di un bucket
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`);
});
}
Riferimenti SDK
Ripristina temporaneamente un oggetto
Informazioni dettagliate sul ripristino dei parametri della richiesta sono disponibili nella Guida di riferimento 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`);
});
}
Valori chiave
<number-of-days>- Numero di giorni per cui conservare il file ripristinato
Riferimenti SDK
Visualizza le informazioni HEAD per un oggetto
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`);
});
}
Riferimenti SDK
Aggiornamento dei metadati
Esistono due modi per aggiornare i metadati in un oggetto esistente:
- Una richiesta
PUTcon i nuovi metadati e il contenuto dell'oggetto originale - L'esecuzione di una richiesta
COPYcon i nuovi metadati che specifica l'oggetto originale come origine della copia
Utilizzo di PUT per aggiornare i metadati
Nota: la richiesta " PUT " sovrascrive il contenuto esistente dell'oggetto; pertanto, è necessario prima scaricarlo e poi ricaricarlo con i nuovi metadati.
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`);
});
}
Utilizzo di COPY per aggiornare i metadati
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`);
});
}
Utilizzo di Immutable Object Storage
Aggiunta di una configurazione di protezione ad un bucket esistente
Gli oggetti scritti in un bucket protetto non possono essere eliminati fino a quando il periodo di protezione non è scaduto e tutte le conservazioni a fini legali sull'oggetto non sono stati rimosse. A un oggetto viene dato il valore di conservazione predefinito del bucket, a meno che non venga fornito un valore specifico per l'oggetto quando l'oggetto viene creato. Gli oggetti nei bucket protetti che non sono più sottoposti a conservazione (il periodo di conservazione è scaduto e l'oggetto non ha alcuna conservazione a fini legali), quando vengono sovrascritti sono di nuovo sottoposti a conservazione. Il nuovo periodo di conservazione può essere fornito come parte della richiesta di sovrascrittura dell'oggetto, altrimenti all'oggetto verrà assegnato il tempo di conservazione predefinito del bucket.
I valori supportati minimo e massimo per le impostazioni del periodo di conservazione MinimumRetention, DefaultRetention e MaximumRetention sono, rispettivamente, 0 giorni e 365243 giorni (1000 anni).
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`);
});
}
Controlla la protezione su un bucket
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`);
});
}
Carica un oggetto protetto
Gli oggetti nei bucket protetti che non sono più sottoposti a conservazione (il periodo di conservazione è scaduto e l'oggetto non ha alcuna conservazione a fini legali), quando vengono sovrascritti sono di nuovo sottoposti a conservazione. Il nuovo periodo di conservazione può essere fornito come parte della richiesta di sovrascrittura dell'oggetto, altrimenti all'oggetto verrà assegnato il tempo di conservazione predefinito del bucket.
| Valore | Immettere | Descrizione |
|---|---|---|
Retention-Period |
Numero intero non negativo (secondi) | Il periodo di conservazione da memorizzare sull'oggetto, in secondi. L'oggetto non può essere sovrascritto o eliminato finché l'intervallo di tempo specificato nel periodo di conservazione non è trascorso. Se vengono specificati questi
campo e Retention-Expiration-Date, viene restituito un errore 400. Se non viene specificato nessuno di questi due valori, verrà utilizzato il periodo DefaultRetention del bucket. Zero (0)
è un valore consentito, presumendo che il periodo di conservazione minimo del bucket sia anch'esso 0. |
Retention-expiration-date |
Data (formato ISO 8601) | Data in cui sarà consentito eliminare o modificare l'oggetto. Puoi specificare solo questo valore oppure l'intestazione Retention-Period. Se vengono specificati entrambi, verrà restituito un errore 400. Se non viene specificato
nessuno di questi due valori, verrà utilizzato il periodo DefaultRetention del bucket. |
Retention-legal-hold-id |
stringa | Una singola conservazione a fini legali da applicare all'oggetto. Una conservazione a fini legali è una stringa di caratteri di lunghezza Y. L'oggetto non può essere sovrascritto o eliminato finché non sono state rimosse tutte le conservazioni a fini legali a esso associate. |
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`);
});
}
Aggiungi/rimuovi una conservazione a fini legali a/da un oggetto protetto
L'oggetto può supportare 100 conservazioni a fini legali:
- Un identificativo di conservazione a fini legali è una stringa di una lunghezza massima di 64 caratteri e una lunghezza minima di 1 carattere. I caratteri validi sono lettere, numeri,
!,_,.,*,(,),-e'. - Se l'aggiunta di una specifica conservazione a fini legali comporta il superamento di un totale di 100 conservazioni a fini legali sull'oggetto, la nuova conservazione a fini legali non viene aggiunta e viene restituito un errore
400. - Se un identificativo è troppo lungo, non viene aggiunto all'oggetto e viene restituito un errore
400. - Se un identificativo contiene caratteri non validi, non viene aggiunto all'oggetto e viene restituito un errore
400. - Se un identificativo è già in uso su un oggetto, la conservazione a fini legali esistente non viene modificata e la risposta indica che l'identificativo era già in uso con un errore
409. - Se un oggetto non ha metadati del periodo di conservazione, viene restituito un errore
400e l'aggiunta o la rimozione di una conservazione a fini legali non è consentita.
L'utente che esegue l'aggiunta o la rimozione di una conservazione a fini legali deve disporre delle autorizzazioni di Manager (gestore) per questo bucket.
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`);
});
}
Estendi il periodo di conservazione di un oggetto protetto
Il periodo di conservazione di un oggetto può solo essere esteso. Non può essere ridotto rispetto al valore attualmente configurato.
Il valore di espansione della conservazione è impostato in uno di tre possibili modi:
- ulteriore tempo dal valore corrente (
Additional-Retention-Periodo metodo simile) - nuovo periodo di estensione in secondi (
Extend-Retention-From-Current-Timeo metodo simile) - nuova data di scadenza della conservazione dell'oggetto (
New-Retention-Expiration-Dateo metodo simile)
Il periodo di conservazione attuale memorizzato nei metadati dell'oggetto viene aumentato in misura equivalente al tempo aggiuntivo indicato oppure sostituito con il nuovo valore, a seconda del parametro impostato nella richiesta extendRetention.
In tutti i casi, il parametro di estensione della conservazione viene controllato rispetto al periodo di conservazione attuale e il parametro esteso viene accettato solo se il periodo di conservazione aggiornato è più grande del periodo
di conservazione attuale.
Gli oggetti nei bucket protetti che non sono più sottoposti a conservazione (il periodo di conservazione è scaduto e l'oggetto non ha alcuna conservazione a fini legali), quando vengono sovrascritti sono di nuovo sottoposti a conservazione. Il nuovo periodo di conservazione può essere fornito come parte della richiesta di sovrascrittura dell'oggetto, altrimenti all'oggetto verrà assegnato il tempo di conservazione predefinito del bucket.
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`);
});
}
Elenca le conservazioni a fini legali su un oggetto protetto
Questa operazione restituisce:
- La data di creazione dell'oggetto
- Il periodo di conservazione dell'oggetto in secondi
- Data di scadenza della conservazione calcolata sulla base del periodo e della data di creazione
- Elenco delle conservazioni a fini legali
- Identificativo della conservazione a fini legali
- Data/ora di quando è stata applicata la conservazione a fini legali
Se non ci sono conservazioni a fini legali sull'oggetto, viene restituito un LegalHoldSet vuoto. Se non c'è alcun periodo di conservazione specificato sull'oggetto, viene restituito un errore 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`);
});
}
Crea un sito web statico ospitato
Questa operazione richiede le autorizzazioni, poiché solo al proprietario del bucket è generalmente consentito configurare un bucket per ospitare un sito web statico. I parametri determinano il suffisso predefinito per i visitatori del sito e un documento di errore facoltativo.
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`);
});
}
Passi successivi
Ulteriori dettagli sui singoli metodi e classi possono essere trovati nella documentazione API dell'SDK. Controlla il codice sorgente su GitHub.