Node.js の使用方法 V2
IBM Cloud® Object Storage ( SDK for Node.js v2 )は、 IBM Cloud Object Storage を最大限に活用するための機能を提供しています。
IBM Cloud Object Storage ( SDK for Node.js v2 )は包括的な内容となっており、このガイドの範囲や紙幅では紹介しきれないほど多くの機能や性能を備えています。 クラスおよびメソッドの詳細なドキュメントについては、『 Node.js 』のAPIリファレンスを 参照してください。 ソース・コードは、GitHub リポジトリーにあります。
新機能 v2
IBM Cloud Object Storage ( SDK for Node.js v2 )は、 AWS SDK( v3 )のアーキテクチャに基づいて構築された最新版であり、次のような大幅な改善が図られています:
- モジュール式アーキテクチャ- 必要なコマンドとクライアントのみをインポートする
- プロミスファースト設計- ネイティブな async/await サポートと、より洗練されたエラー処理
- バンドルサイズの縮小- ツリーシェイク可能なモジュールにより、アプリケーションのサイズを縮小
- 最新の JavaScript- ES6+ の機能と TypeScript のサポートを活用
- ミドルウェア・スタック- 拡張可能なリクエスト/レスポンス・パイプライン
- エラー処理の改善- 詳細な情報を含む構造化されたエラー型
v1 から移行する開発者は、「 移行ガイド 」を参照してください。
SDK の取得
IBM のCOS( SDK for Node.js )をインストールする推奨方法は、 Node.js用のnpmパッケージマネージャーを使用する ことです。ターミナルウィンドウに以下を入力するだけです:
npm install ibm-cos-sdk-v2
前提条件
- Node.js バージョン18以降- このSDKには、 Node.js のバージョン18以降が必要です。
- のインスタンス IBM Cloud Object Storage
- 以下のAPIキー IBM Cloud Identity and Access Management
Writer以上の権限を持つAPIキー - 現在操作している COS インスタンスの ID
- トークン取得エンドポイント
- サービス・エンドポイント
これらの値は、 IBM Cloud コンソール内の「 「サービス認証情報」の生成 」で確認できます。
パッケージのインポート
SDKをインストールした後、SDKを使用するには、次の例に示すように、 Node.js アプリケーションに必要なパッケージをインポートする必要があります
CommonJS:
const { S3Client } = require('ibm-cos-sdk-v2');
const {
CreateBucketCommand,
ListBucketsCommand,
PutObjectCommand,
GetObjectCommand
} = require('ibm-cos-sdk-v2');
ESモジュール / TypeScript:
import { S3Client } from 'ibm-cos-sdk-v2';
import {
CreateBucketCommand,
ListBucketsCommand,
PutObjectCommand,
GetObjectCommand
} from 'ibm-cos-sdk-v2';
SDK リファレンス
コア・クラス
- S3Client- 連携するための主要なクライアント IBM Cloud Object Storage
- コマンドクラス- 各操作には、対応するコマンドクラスが存在します(例:
PutObjectCommand、GetObjectCommand)
構成
- S3Client コンストラクタ- 設定オプションを指定して、新しい S3 クライアントを作成します
- region- クライアントのリージョンを設定します
- endpoint- サービスエンドポイントを設定します URL
- 認証情報- 認証情報を設定します
クライアントの作成とサービス認証情報の取得
IBM Cloud Object Storage に接続するために、資格情報 (API キーとサービス・インスタンス ID) を指定することによりクライアントが作成および構成されます。 これらの値は、資格情報ファイルまたは環境変数から自動的に入手することもできます。
資格情報は、サービス資格情報を作成するか、CLI を介して見つけることができます。
IBM によるIAM認証の使用
以下の例は、API キーを使用した IBM のIAM認証によるクライアントの作成方法を示しています
CommonJS:
const { S3Client } = require('ibm-cos-sdk-v2');
// Initialize client
const client = new S3Client({
endpoint: 'https://s3.us-south.cloud-object-storage.appdomain.cloud',
region: 'us-south',
credentials: {
apiKey: '<API_KEY>',
serviceInstanceId: '<SERVICE_INSTANCE_ID>'
}
});
TypeScript:
import { S3Client } from 'ibm-cos-sdk-v2';
const client = new S3Client({
endpoint: 'https://s3.us-south.cloud-object-storage.appdomain.cloud',
region: 'us-south',
credentials: {
apiKey: '<API_KEY>',
serviceInstanceId: '<SERVICE_INSTANCE_ID>'
}
});
必要な設定オプションは以下の通りです:
endpoint- COSバケットのリージョンに対応するエンドポイント URLregion- バケットが配置されているリージョンcredentials.apiKey- 適切な権限が設定された IBM Cloud APIキーcredentials.serviceInstanceId- COSインスタンスのCRN(クラウドリソース名)
コード例
以下の例では、前のセクションで示したように、すでにクライアントを作成済みであることを前提としています。
バケットの作成
const { CreateBucketCommand } = require('ibm-cos-sdk-v2');
const command = new CreateBucketCommand({
Bucket: 'my-new-bucket',
CreateBucketConfiguration: {
LocationConstraint: 'us-south-standard'
}
});
try {
const response = await client.send(command);
console.log('Bucket created successfully');
} catch (err) {
console.error('Error creating bucket:', err);
}
利用可能なバケットの一覧表示
const { ListBucketsCommand } = require('ibm-cos-sdk-v2');
try {
const command = new ListBucketsCommand({});
const response = await client.send(command);
console.log('Buckets:');
if (response.Buckets && response.Buckets.length > 0) {
response.Buckets.forEach(bucket => {
console.log(` - ${bucket.Name} (created: ${bucket.CreationDate})`);
});
} else {
console.log(' No buckets found');
}
} catch (err) {
console.error('Failed to list buckets:', err);
}
詳細情報を含むバケットの一覧表示
IBM Cloud Object Storage バケットに関する追加情報を返す、拡張されたリスト操作を提供します:
const { ListBucketsExtendedCommand } = require('ibm-cos-sdk-v2');
const command = new ListBucketsExtendedCommand({
IBMServiceInstanceId: '<SERVICE_INSTANCE_ID>',
Prefix: 'my-bucket-prefix',
MaxKeys: 100
});
try {
const response = await client.send(command);
console.log('Extended Bucket Information:');
if (response.Buckets && response.Buckets.length > 0) {
response.Buckets.forEach(bucket => {
console.log(` Bucket: ${bucket.Name}`);
console.log(` Location: ${bucket.LocationConstraint}`);
console.log(` Created: ${bucket.CreationDate}`);
});
} else {
console.log(' No buckets found');
}
} catch (err) {
console.error('Failed to list buckets:', err);
}
バケットの位置の取得
const { GetBucketLocationCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const command = new GetBucketLocationCommand({
Bucket: bucketName
});
try {
const response = await client.send(command);
console.log(`Bucket '${bucketName}' is located in: ${response.LocationConstraint}`);
} catch (err) {
console.error('Failed to get bucket location:', err);
}
バケットの削除
const { DeleteBucketCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket-to-delete';
const command = new DeleteBucketCommand({
Bucket: bucketName
});
try {
await client.send(command);
console.log(`Bucket '${bucketName}' deleted successfully`);
} catch (err) {
console.error('Failed to delete bucket:', err);
}
注 :バケットを削除するには、そのバケットが空である必要があります。
オブジェクトをバケットにアップロードする
const { PutObjectCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const objectKey = 'my-object.txt';
const content = 'Hello, IBM Cloud Object Storage!';
const command = new PutObjectCommand({
Bucket: bucketName,
Key: objectKey,
Body: content
});
try {
const response = await client.send(command);
console.log(`Object '${objectKey}' uploaded successfully`);
console.log(`ETag: ${response.ETag}`);
} catch (err) {
console.error('Failed to upload object:', err);
}
バケットからオブジェクトをダウンロードする
const { GetObjectCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const objectKey = 'my-object.txt';
const command = new GetObjectCommand({
Bucket: bucketName,
Key: objectKey
});
try {
const response = await client.send(command);
// Convert stream to buffer
const chunks = [];
for await (const chunk of response.Body) {
chunks.push(chunk);
}
const buffer = Buffer.concat(chunks);
console.log(`Object '${objectKey}' downloaded successfully`);
console.log(`Content-Type: ${response.ContentType}`);
console.log(`Content-Length: ${response.ContentLength} bytes`);
console.log(`Size: ${buffer.length} bytes`);
} catch (err) {
console.error('Failed to download object:', err);
}
バケット内のオブジェクトのリスト表示
const { ListObjectsV2Command } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const command = new ListObjectsV2Command({
Bucket: bucketName,
MaxKeys: 1000
});
try {
const response = await client.send(command);
console.log(`Objects in bucket '${bucketName}':`);
if (response.Contents && response.Contents.length > 0) {
response.Contents.forEach(object => {
console.log(` - ${object.Key} (size: ${object.Size} bytes, modified: ${object.LastModified})`);
});
console.log(`\nTotal objects: ${response.Contents.length}`);
} else {
console.log(' No objects found');
}
} catch (err) {
console.error('Failed to list objects:', err);
}
オブジェクトのコピー
const { CopyObjectCommand } = require('ibm-cos-sdk-v2');
const sourceBucket = 'source-bucket';
const sourceKey = 'source-object.txt';
const destinationBucket = 'destination-bucket';
const destinationKey = 'destination-object.txt';
// CopySource format: source-bucket/source-key
const copySource = `${sourceBucket}/${sourceKey}`;
const command = new CopyObjectCommand({
Bucket: destinationBucket,
Key: destinationKey,
CopySource: copySource
});
try {
const response = await client.send(command);
console.log('Object copied successfully');
if (response.CopyObjectResult) {
console.log(`ETag: ${response.CopyObjectResult.ETag}`);
}
} catch (err) {
console.error('Failed to copy object:', err);
}
オブジェクトの削除
const { DeleteObjectCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const objectKey = 'object-to-delete.txt';
const command = new DeleteObjectCommand({
Bucket: bucketName,
Key: objectKey
});
try {
await client.send(command);
console.log(`Object '${objectKey}' deleted successfully`);
} catch (err) {
console.error('Failed to delete object:', err);
}
複数のオブジェクトの削除
const { DeleteObjectsCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const objectsToDelete = [
'object1.txt',
'object2.txt',
'object3.txt'
];
// Build delete request
const objects = objectsToDelete.map(key => ({ Key: key }));
const command = new DeleteObjectsCommand({
Bucket: bucketName,
Delete: {
Objects: objects,
Quiet: false
}
});
try {
const response = await client.send(command);
console.log('Delete operation completed');
if (response.Deleted && response.Deleted.length > 0) {
console.log(`Successfully deleted ${response.Deleted.length} object(s):`);
response.Deleted.forEach(deleted => {
console.log(` - ${deleted.Key}`);
});
}
if (response.Errors && response.Errors.length > 0) {
console.log(`\nFailed to delete ${response.Errors.length} object(s):`);
response.Errors.forEach(error => {
console.log(` - ${error.Key}: ${error.Message}`);
});
}
} catch (err) {
console.error('Failed to delete objects:', err);
}
オブジェクトのメタデータの取得 (HEAD)
const { HeadObjectCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const objectKey = 'my-object.txt';
const command = new HeadObjectCommand({
Bucket: bucketName,
Key: objectKey
});
try {
const response = await client.send(command);
console.log(`Object Metadata for '${objectKey}':`);
console.log(` Content-Type: ${response.ContentType}`);
console.log(` Content-Length: ${response.ContentLength} bytes`);
console.log(` ETag: ${response.ETag}`);
console.log(` Last-Modified: ${response.LastModified}`);
if (response.Metadata && Object.keys(response.Metadata).length > 0) {
console.log(' Custom Metadata:');
for (const [key, value] of Object.entries(response.Metadata)) {
console.log(` ${key}: ${value}`);
}
}
} catch (err) {
console.error('Failed to get object metadata:', err);
}
複数パーツ・アップロードの使用
大容量のオブジェクトの場合、マルチパートアップロードを利用することで、スループットが向上し、アップロードの再開も可能になります。 各パートは、少なくとも5 MB以上である必要があります(最後のパートを除く)。
手動による複数ファイルのアップロード:
const {
CreateMultipartUploadCommand,
UploadPartCommand,
CompleteMultipartUploadCommand,
AbortMultipartUploadCommand
} = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const objectKey = 'large-object.dat';
try {
// Step 1: Initiate multipart upload
const createCommand = new CreateMultipartUploadCommand({
Bucket: bucketName,
Key: objectKey
});
const createResponse = await client.send(createCommand);
const uploadId = createResponse.UploadId;
console.log(`Multipart upload initiated with ID: ${uploadId}`);
// Step 2: Upload parts (minimum 5MB per part except last)
const completedParts = [];
const minPartSize = 5 * 1024 * 1024; // 5MB
// Create sample parts
const parts = [
'A'.repeat(minPartSize),
'B'.repeat(minPartSize)
];
for (let i = 0; i < parts.length; i++) {
const partNumber = i + 1;
const uploadPartCommand = new UploadPartCommand({
Bucket: bucketName,
Key: objectKey,
PartNumber: partNumber,
UploadId: uploadId,
Body: parts[i]
});
try {
const uploadResponse = await client.send(uploadPartCommand);
completedParts.push({
ETag: uploadResponse.ETag,
PartNumber: partNumber
});
console.log(`Part ${partNumber} uploaded (ETag: ${uploadResponse.ETag})`);
} catch (err) {
// Abort multipart upload on error
const abortCommand = new AbortMultipartUploadCommand({
Bucket: bucketName,
Key: objectKey,
UploadId: uploadId
});
await client.send(abortCommand);
throw err;
}
}
// Step 3: Complete multipart upload
const completeCommand = new CompleteMultipartUploadCommand({
Bucket: bucketName,
Key: objectKey,
UploadId: uploadId,
MultipartUpload: {
Parts: completedParts
}
});
const completeResponse = await client.send(completeCommand);
console.log('Multipart upload completed successfully');
console.log(`Location: ${completeResponse.Location}`);
console.log(`ETag: ${completeResponse.ETag}`);
} catch (err) {
console.error('Failed to complete multipart upload:', err);
}
アップロードマネージャーの使用(推奨):
複数ファイルのアップロードを簡単に行うには、 @ibm-cos/lib-storage パッケージを使用してください:
const { Upload } = require('@ibm-cos/lib-storage');
const { S3Client } = require('ibm-cos-sdk-v2');
const fs = require('fs');
const fileStream = fs.createReadStream('large-file.bin');
const upload = new Upload({
client: client,
params: {
Bucket: 'my-bucket',
Key: 'large-file.bin',
Body: fileStream
},
queueSize: 4, // Concurrent parts
partSize: 5 * 1024 * 1024, // 5MB parts
leavePartsOnError: false
});
// Track progress
upload.on('httpUploadProgress', (progress) => {
console.log('Upload progress:', progress);
});
try {
const result = await upload.done();
console.log('Upload completed:', result);
} catch (err) {
console.error('Upload failed:', err);
}
マルチパートアップロードの一覧表示
const { ListMultipartUploadsCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const command = new ListMultipartUploadsCommand({
Bucket: bucketName
});
try {
const response = await client.send(command);
console.log(`In-progress multipart uploads in bucket '${bucketName}':`);
if (response.Uploads && response.Uploads.length > 0) {
response.Uploads.forEach(upload => {
console.log(` Key: ${upload.Key}`);
console.log(` Upload ID: ${upload.UploadId}`);
console.log(` Initiated: ${upload.Initiated}`);
});
} else {
console.log(' No in-progress uploads found');
}
} catch (err) {
console.error('Failed to list multipart uploads:', err);
}
複数ファイルのアップロードに含まれるファイルの一覧表示
進行中の複数ファイルアップロードについて、アップロード済みのすべてのファイルを一覧表示します。 アップロードを完了する前に、進捗状況を確認したり、ETagを収集したりするのに便利です。
const { ListPartsCommand } = require('ibm-cos-sdk-v2');
const command = new ListPartsCommand({
Bucket: 'my-bucket',
Key: 'my-large-object',
UploadId: 'YOUR_UPLOAD_ID_HERE'
});
try {
const response = await client.send(command);
console.log('Parts listed successfully');
if (response.Parts && response.Parts.length > 0) {
response.Parts.forEach(p =>
console.log(' - Part', p.PartNumber, '| ETag:', p.ETag, '| Size:', p.Size, 'bytes')
);
} else {
console.log('No parts found.');
}
} catch (err) {
console.error('Error listing parts:', err);
}
既存のオブジェクトからパーツをコピーする
既存のオブジェクトからコピーして、パーツをアップロードします。 ソースデータがすでにCOSに存在している場合は、生のバイトデータをアップロードする代わりに、これを使用してください。
const { UploadPartCopyCommand } = require('ibm-cos-sdk-v2');
const command = new UploadPartCopyCommand({
Bucket: 'my-bucket',
Key: 'my-large-object',
UploadId: 'YOUR_UPLOAD_ID_HERE',
PartNumber: 1,
CopySource: 'my-bucket/source-object-key'
});
try {
const response = await client.send(command);
console.log('Part copy uploaded successfully');
console.log('ETag:', response.CopyPartResult?.ETag);
} catch (err) {
console.error('Error uploading part copy:', err);
}
バケットのライフサイクル設定を行う
アーカイブポリシーを使用すると、指定した期間が経過した後、オブジェクトを自動的にアーカイブストレージクラスに移行させることができます:
const { PutBucketLifecycleConfigurationCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
// Configure lifecycle rule to expire objects after 30 days
const command = new PutBucketLifecycleConfigurationCommand({
Bucket: bucketName,
LifecycleConfiguration: {
Rules: [
{
Id: 'delete-old-logs',
Status: 'Enabled',
Filter: {
Prefix: 'logs/',
},
Expiration: {
Days: 30,
},
},
{
Id: 'cleanup-multipart-uploads',
Status: 'Enabled',
Filter: {
Prefix: '',
},
AbortIncompleteMultipartUpload: {
DaysAfterInitiation: 7,
},
},
]
}
});
try {
await client.send(command);
console.log(`Lifecycle configuration set for bucket '${bucketName}'`);
} catch (err) {
console.error('Failed to set lifecycle configuration:', err);
}
バケットのライフサイクル設定の取得
const { GetBucketLifecycleConfigurationCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const command = new GetBucketLifecycleConfigurationCommand({
Bucket: bucketName
});
try {
const response = await client.send(command);
console.log(`Lifecycle rules for bucket '${bucketName}':`);
if (response.Rules && response.Rules.length > 0) {
response.Rules.forEach(rule => {
console.log(` Rule ID: ${rule.ID}`);
console.log(` Status: ${rule.Status}`);
if (rule.Transitions && rule.Transitions.length > 0) {
rule.Transitions.forEach(transition => {
console.log(` Transition to ${transition.StorageClass} after ${transition.Days} days`);
});
}
});
} else {
console.log(' No lifecycle rules found');
}
} catch (err) {
console.error('Failed to get lifecycle configuration:', err);
}
バケットのバージョン管理を有効にする
const { PutBucketVersioningCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const command = new PutBucketVersioningCommand({
Bucket: bucketName,
VersioningConfiguration: {
// Valid values: 'Enabled' | 'Suspended'
Status: 'Enabled',
},
});
try {
await client.send(command);
console.log(`Versioning enabled for bucket '${bucketName}'`);
} catch (err) {
console.error('Failed to enable versioning:', err);
}
オブジェクトのバージョンの一覧表示
const { ListObjectVersionsCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const command = new ListObjectVersionsCommand({
Bucket: bucketName
});
try {
const response = await client.send(command);
console.log(`Object versions in bucket '${bucketName}':`);
if (response.Versions && response.Versions.length > 0) {
response.Versions.forEach(version => {
console.log(` Key: ${version.Key}`);
console.log(` Version ID: ${version.VersionId}`);
console.log(` Is Latest: ${version.IsLatest}`);
console.log(` Last Modified: ${version.LastModified}`);
});
} else {
console.log(' No versions found');
}
} catch (err) {
console.error('Failed to list object versions:', err);
}
CORS の設定
const { PutBucketCorsCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
// Set CORS configuration
const command = new PutBucketCorsCommand({
Bucket: bucketName,
CORSConfiguration: {
CORSRules: [
{
AllowedHeaders: ['*'],
AllowedMethods: ['GET', 'PUT', 'POST', 'DELETE'],
AllowedOrigins: ['https://example.com'],
ExposeHeaders: ['ETag'],
MaxAgeSeconds: 3000
}
]
}
});
try {
await client.send(command);
console.log(`CORS configuration set for bucket '${bucketName}'`);
} catch (err) {
console.error('Failed to set CORS configuration:', err);
}
オブジェクトのタグ付けの設定
const { PutObjectTaggingCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const objectKey = 'my-object.txt';
// Set object tags
const command = new PutObjectTaggingCommand({
Bucket: bucketName,
Key: objectKey,
Tagging: {
TagSet: [
{
Key: 'Department',
Value: 'Finance'
},
{
Key: 'Project',
Value: 'Q4-2024'
},
{
Key: 'Classification',
Value: 'Confidential'
}
]
}
});
try {
await client.send(command);
console.log(`Tags set for object '${objectKey}'`);
} catch (err) {
console.error('Failed to set object tags:', err);
}
オブジェクトタグの取得
const { GetObjectTaggingCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-bucket';
const objectKey = 'my-object.txt';
const command = new GetObjectTaggingCommand({
Bucket: bucketName,
Key: objectKey
});
try {
const response = await client.send(command);
console.log(`Tags for object '${objectKey}':`);
if (response.TagSet && response.TagSet.length > 0) {
response.TagSet.forEach(tag => {
console.log(` ${tag.Key}: ${tag.Value}`);
});
} else {
console.log(' No tags found');
}
} catch (err) {
console.error('Failed to get object tags:', err);
}
アーカイブされたオブジェクトの復元
アーカイブストレージクラス内のオブジェクトは、アクセスする前に復元する必要があります:
const command = new RestoreObjectCommand({
Bucket: bucketName,
Key: objectKey,
RestoreRequest: {
Days: 7,
GlacierJobParameters: {
Tier: 'Bulk',
},
},
});
try {
await client.send(command);
console.log('Object restore initiated successfully');
console.log(
'Retrieval time depends on storage class: Vault typically 1-5 hours, Cold Vault typically 5-12 hours.'
);
} catch (err) {
console.error('Failed to restore object:', err);
}
注 : IBM Cloud Object Storage では、VaultおよびCold Vaultストレージクラスからオブジェクトを復元する場合、 Bulk の取得階層のみがサポートされています。
オブジェクトの保持期間の設定
ガバナンスモード :特定のIAM権限を持つユーザーは、保存期間中にオブジェクトのバージョンを削除できます。
コンプライアンスモード :保存期間中は、どのユーザーもオブジェクトのバージョンを削除することはできません。
const { PutObjectRetentionCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-protected-bucket';
const objectKey = 'important-document.pdf';
// Set retention until a specific date
const retainUntil = new Date();
retainUntil.setDate(retainUntil.getDate() + 30);
const command = new PutObjectRetentionCommand({
Bucket: bucketName,
Key: objectKey,
Retention: {
Mode: 'COMPLIANCE',
RetainUntilDate: retainUntil,
},
});
try {
await client.send(command);
console.log('Object retention set successfully');
console.log('RetainUntil:', retainUntil.toISOString());
} catch (err) {
console.error('Error:', err.message);
}
オブジェクトの保持期間の取得
const { GetObjectRetentionCommand } = require('ibm-cos-sdk-v2');
const bucketName = 'my-protected-bucket';
const objectKey = 'important-document.pdf';
const command = new GetObjectRetentionCommand({
Bucket: bucketName,
Key: objectKey
});
try {
const response = await client.send(command);
console.log('Object retention retrieved successfully');
console.log('Mode:', response.Retention?.Mode);
console.log('RetainUntilDate:', response.Retention?.RetainUntilDate);
} catch (err) {
console.error('Error:', err.message);
}
Object Lock を使用したバケットの作成 ( S3 )
S3 オブジェクトロックは、所定の保存期間中、あるいは無期限に、オブジェクトが削除されたり上書きされたりすることを防ぎます。 オブジェクトロックは、バケットの作成時に有効にする必要があります。既存のバケットに追加することはできません。
ガバナンスモード :特定のIAM権限を持つユーザーは、保存期間中にオブジェクトのバージョンを削除できます。
コンプライアンスモード :保存期間中は、どのユーザーもオブジェクトのバージョンを削除することはできません。
このセクションでは、 S3-compatible のオブジェクトロックについて解説します。 IBM のCOS固有のWORM保護については、「 バケット保護(WORM)の設定 」および「 リーガルホールドの管理 」を参照してください。
const {
CreateBucketCommand,
PutObjectLockConfigurationCommand
} = require('ibm-cos-sdk-v2');
// Step 1: Create bucket with Object Lock enabled
const createCommand = new CreateBucketCommand({
Bucket: 'my-locked-bucket',
ObjectLockEnabledForBucket: true
});
try {
await client.send(createCommand);
console.log('Bucket created with Object Lock enabled');
} catch (err) {
console.error('Error creating bucket:', err.message);
}
// Step 2: Set default retention rule
const lockConfigCommand = new PutObjectLockConfigurationCommand({
Bucket: 'my-locked-bucket',
ObjectLockConfiguration: {
ObjectLockEnabled: 'Enabled',
Rule: {
DefaultRetention: {
Mode: 'GOVERNANCE',
Days: 30
}
}
}
});
try {
await client.send(lockConfigCommand);
console.log('Default Object Lock configuration set successfully');
} catch (err) {
console.error('Error setting lock config:', err.message);
}
オブジェクトロックの設定
バケットにアップロードされるすべての新しいオブジェクトに適用されるデフォルトの保存期間ルールを設定または更新します。
const { PutObjectLockConfigurationCommand } = require('ibm-cos-sdk-v2');
const command = new PutObjectLockConfigurationCommand({
Bucket: 'my-object-lock-bucket',
ObjectLockConfiguration: {
ObjectLockEnabled: 'Enabled',
Rule: {
DefaultRetention: {
Mode: 'COMPLIANCE',
Days: 2
}
}
}
});
try {
await client.send(command);
console.log('Object lock configuration set successfully');
} catch (err) {
console.error('Error:', err.message);
}
オブジェクトロックの設定を取得する
const { GetObjectLockConfigurationCommand } = require('ibm-cos-sdk-v2');
const command = new GetObjectLockConfigurationCommand({
Bucket: 'my-object-lock-bucket'
});
try {
const response = await client.send(command);
console.log('Object lock configuration retrieved successfully');
console.log('ObjectLockEnabled:', response.ObjectLockConfiguration?.ObjectLockEnabled);
console.log('Rule:', JSON.stringify(response.ObjectLockConfiguration?.Rule, null, 2));
} catch (err) {
console.error('Error:', err.message);
}
S3 オブジェクトのロック設定:法的保存措置
オブジェクトに対するリーガルホールドを設定または解除します。 リーガルホールドが有効な間は、そのオブジェクトの保存期間にかかわらず、そのオブジェクトを削除することはできません。
const { PutObjectLegalHoldCommand } = require('ibm-cos-sdk-v2');
const command = new PutObjectLegalHoldCommand({
Bucket: 'my-locked-bucket',
Key: 'my-file.txt',
LegalHold: {
Status: 'ON' // 'ON' or 'OFF'
}
});
try {
await client.send(command);
console.log('Legal hold set successfully');
} catch (err) {
console.error('Error:', err.message);
}
S3 オブジェクトのロックによる法的保存措置の実施
const { GetObjectLegalHoldCommand } = require('ibm-cos-sdk-v2');
const command = new GetObjectLegalHoldCommand({
Bucket: 'my-locked-bucket',
Key: 'my-file.txt'
});
try {
const response = await client.send(command);
console.log('Legal hold retrieved successfully');
console.log('Status:', response.LegalHold?.Status);
} catch (err) {
console.error('Error:', err.message);
}
バケットの存在確認 (HEAD)
const { HeadBucketCommand } = require('ibm-cos-sdk-v2');
const command = new HeadBucketCommand({
Bucket: 'my-bucket'
});
try {
await client.send(command);
console.log('Bucket exists');
} catch (err) {
if (err.name === 'NotFound') {
console.log('Bucket does not exist');
} else {
console.error('Error checking bucket:', err);
}
}
ファイルからのストリーミングアップロード
const fs = require('fs');
const { PutObjectCommand } = require('ibm-cos-sdk-v2');
const fileStream = fs.createReadStream('large-file.bin');
const command = new PutObjectCommand({
Bucket: 'my-bucket',
Key: 'large-file.bin',
Body: fileStream
});
try {
const response = await client.send(command);
console.log('File uploaded successfully');
} catch (err) {
console.error('Error uploading file:', err);
}
ファイルへのストリーミングダウンロード
const fs = require('fs');
const { GetObjectCommand } = require('ibm-cos-sdk-v2');
const command = new GetObjectCommand({
Bucket: 'my-bucket',
Key: 'large-file.bin'
});
try {
const response = await client.send(command);
const fileStream = fs.createWriteStream('downloaded-file.bin');
response.Body.pipe(fileStream);
await new Promise((resolve, reject) => {
fileStream.on('finish', resolve);
fileStream.on('error', reject);
response.Body.on('error', reject);
});
console.log('File downloaded successfully');
} catch (err) {
console.error('Error downloading file:', err);
}
ページネーション機能付きですべてのオブジェクトを一覧表示する
v2 SDK には、結果の一部のみが返される操作向けに、組み込みのページネーション機能が用意されています。
ページネーターの使用(推奨):
const { paginateListObjectsV2 } = require('ibm-cos-sdk-v2');
async function listAllObjects(bucket, prefix) {
const allObjects = [];
const paginator = paginateListObjectsV2(
{ client: client, pageSize: 1000 },
{ Bucket: bucket, Prefix: prefix }
);
try {
for await (const page of paginator) {
if (page.Contents) {
allObjects.push(...page.Contents);
}
}
console.log('Total objects:', allObjects.length);
return allObjects;
} catch (err) {
console.error('Error listing objects:', err);
throw err;
}
}
手動によるページネーション:
const { ListObjectsV2Command } = require('ibm-cos-sdk-v2');
async function listAllObjects(bucket, prefix) {
const allObjects = [];
let continuationToken = undefined;
do {
const command = new ListObjectsV2Command({
Bucket: bucket,
Prefix: prefix,
ContinuationToken: continuationToken
});
const response = await client.send(command);
if (response.Contents) {
allObjects.push(...response.Contents);
}
continuationToken = response.NextContinuationToken;
} while (continuationToken);
console.log('Total objects:', allObjects.length);
return allObjects;
}
事前署名済みURLの生成
事前署名済みURLを使用すると、オブジェクトへの一時的な、認証不要のアクセスが可能になります。 まず、presigner パッケージをインストールしてください:
npm install @ibm-cos/s3-request-presigner
事前署名済み GET URL (ダウンロード):
const { GetObjectCommand } = require('ibm-cos-sdk-v2');
const { getSignedUrl } = require('@ibm-cos/s3-request-presigner');
const command = new GetObjectCommand({
Bucket: 'my-bucket',
Key: 'my-object.txt'
});
try {
const url = await getSignedUrl(client, command, { expiresIn: 3600 });
console.log('Presigned URL:', url);
} catch (err) {
console.error('Error generating presigned URL:', err);
}
事前署名済みPUT URL (アップロード):
const { PutObjectCommand } = require('ibm-cos-sdk-v2');
const { getSignedUrl } = require('@ibm-cos/s3-request-presigner');
const command = new PutObjectCommand({
Bucket: 'my-bucket',
Key: 'upload-object.txt',
ContentType: 'text/plain'
});
try {
const url = await getSignedUrl(client, command, { expiresIn: 3600 });
console.log('Presigned PUT URL:', url);
} catch (err) {
console.error('Error generating presigned URL:', err);
}
CORS の設定を取得する
const { GetBucketCorsCommand } = require('ibm-cos-sdk-v2');
const command = new GetBucketCorsCommand({
Bucket: 'my-bucket'
});
try {
const response = await client.send(command);
console.log('CORS rules:', response.CORSRules);
} catch (err) {
console.error('Error getting CORS configuration:', err);
}
CORS の設定を削除する
const { DeleteBucketCorsCommand } = require('ibm-cos-sdk-v2');
const command = new DeleteBucketCorsCommand({
Bucket: 'my-bucket'
});
try {
await client.send(command);
console.log('Bucket CORS configuration deleted successfully');
} catch (err) {
console.error('Error deleting CORS:', err);
}
カスタムメタデータを含むオブジェクトのアップロード
const { PutObjectCommand } = require('ibm-cos-sdk-v2');
const command = new PutObjectCommand({
Bucket: 'my-bucket',
Key: 'my-object.txt',
Body: 'content',
Metadata: {
'author': 'John Doe',
'department': 'Engineering'
}
});
try {
await client.send(command);
console.log('Object uploaded with metadata');
} catch (err) {
console.error('Error uploading object:', err);
}
バケットのタグ付けの設定
const { PutBucketTaggingCommand } = require('ibm-cos-sdk-v2');
const command = new PutBucketTaggingCommand({
Bucket: 'my-bucket',
Tagging: {
TagSet: [
{ Key: 'Environment', Value: 'Production' },
{ Key: 'Project', Value: 'WebApp' }
]
}
});
try {
await client.send(command);
console.log('Bucket tags updated');
} catch (err) {
console.error('Error updating bucket tags:', err);
}
バケットのライフサイクル設定の削除
const { DeleteBucketLifecycleCommand } = require('ibm-cos-sdk-v2');
const command = new DeleteBucketLifecycleCommand({
Bucket: 'my-bucket'
});
try {
await client.send(command);
console.log('Lifecycle configuration deleted successfully');
} catch (err) {
console.error('Error deleting lifecycle:', err);
}
バケットのACLの設定
const { PutBucketAclCommand } = require('ibm-cos-sdk-v2');
const command = new PutBucketAclCommand({
Bucket: 'my-bucket',
ACL: 'public-read'
});
try {
await client.send(command);
console.log('Bucket ACL updated');
} catch (err) {
console.error('Error updating bucket ACL:', err);
}
バケットのACLを取得する
const { GetBucketAclCommand } = require('ibm-cos-sdk-v2');
const command = new GetBucketAclCommand({
Bucket: 'my-bucket'
});
try {
const response = await client.send(command);
console.log('Bucket ACL retrieved successfully');
console.log('Owner:', response.Owner);
console.log('Grants:', response.Grants);
} catch (err) {
console.error('Error getting bucket ACL:', err);
}
オブジェクトのACLの設定
const { PutObjectAclCommand } = require('ibm-cos-sdk-v2');
const command = new PutObjectAclCommand({
Bucket: 'my-bucket',
Key: 'my-object.txt',
ACL: 'public-read'
});
try {
await client.send(command);
console.log('Object ACL updated');
} catch (err) {
console.error('Error updating object ACL:', err);
}
オブジェクトのACLを取得する
const { GetObjectAclCommand } = require('ibm-cos-sdk-v2');
const command = new GetObjectAclCommand({
Bucket: 'my-bucket',
Key: 'my-object.txt'
});
try {
const response = await client.send(command);
console.log('Object ACL retrieved successfully');
console.log('Owner:', response.Owner);
console.log('Grants:', response.Grants);
} catch (err) {
console.error('Error getting object ACL:', err);
}
バージョン管理の状態の確認
const { GetBucketVersioningCommand } = require('ibm-cos-sdk-v2');
const command = new GetBucketVersioningCommand({ Bucket: 'my-bucket' });
try {
const response = await client.send(command);
console.log('Bucket versioning configuration retrieved successfully');
console.log('Status:', response.Status);
// MFADelete is always undefined for IBM COS.
console.log('MFADelete:', response.MFADelete);
} catch (err) {
console.error('Error:', err.message);
}
特定のオブジェクトのバージョンを取得する
const { GetObjectCommand } = require('ibm-cos-sdk-v2');
const command = new GetObjectCommand({
Bucket: 'my-bucket',
Key: 'my-file.txt',
VersionId: '<VERSION_ID>'
});
try {
const response = await client.send(command);
console.log('Version ID:', response.VersionId);
// Stream response.Body to a file or buffer as needed.
} catch (err) {
console.error('Error:', err.message);
}
バージョン管理されたバケットへのオブジェクトのアップロード
バージョン管理が有効になっている場合、 PutObjectCommand を呼び出すたびに新しいバージョンが作成されます。 この回答には、新しい VersionId が含まれています。
const { PutObjectCommand } = require('ibm-cos-sdk-v2');
const command = new PutObjectCommand({
Bucket: 'my-versioned-bucket',
Key: 'my-file.txt',
Body: 'Hello, World!'
});
try {
const response = await client.send(command);
console.log('Object uploaded successfully');
console.log('Version ID:', response.VersionId);
} catch (err) {
console.error('Error:', err.message);
}
特定のオブジェクトのバージョンを削除する
オブジェクトの特定のバージョンを、その VersionId を含めることで、完全に削除します。 バージョン管理されたバケットにバージョンIDがない場合、代わりに削除マーカーが作成されます。
const { DeleteObjectCommand } = require('ibm-cos-sdk-v2');
const command = new DeleteObjectCommand({
Bucket: 'my-versioned-bucket',
Key: 'my-file.txt',
VersionId: 'YOUR_VERSION_ID_HERE'
});
try {
const response = await client.send(command);
console.log('Object version deleted successfully');
console.log('Deleted Version ID:', response.VersionId);
console.log('Delete Marker:', response.DeleteMarker ? 'Yes' : 'No');
} catch (err) {
console.error('Error:', err.message);
}
バケット保護(WORM)の設定
IBM Cloud Object Storage コンプライアンスおよびデータ保持のため、WORM(Write-Once-Read-Many)バケット保護機能をサポートしています。
バケット保護の設定:
const { PutBucketProtectionConfigurationCommand } = require('ibm-cos-sdk-v2');
const command = new PutBucketProtectionConfigurationCommand({
Bucket: 'my-protected-bucket',
ProtectionConfiguration: {
Status: 'Retention',
MinimumRetention: { Days: 1 },
DefaultRetention: { Days: 30 },
MaximumRetention: { Days: 365 },
},
});
try {
await client.send(command);
console.log('Bucket protection configuration set successfully');
} catch (err) {
console.error('Error configuring protection:', err.message);
}
バケットの保護方法:
const { GetBucketProtectionConfigurationCommand } = require('ibm-cos-sdk-v2');
const command = new GetBucketProtectionConfigurationCommand({
Bucket: 'my-protected-bucket'
});
try {
const response = await client.send(command);
console.log('Bucket protection configuration retrieved successfully');
console.log('Response:', JSON.stringify(response, null, 2));
} catch (err) {
console.error('Error getting protection config:', err);
}
法的保存命令の管理
法的保存命令により、保存期間の満了にかかわらず、オブジェクトの削除は阻止されます。 各保留には一意のIDが割り当てられており、オブジェクトを削除するには、すべての保留を明示的に解除する必要があります。
注 :法的保存措置を適用するには、バケットに「 IBM 」のCOS保護設定が設定されている必要があります。
法的保存措置の設定:
const { AddLegalHoldCommand } = require('ibm-cos-sdk-v2');
const command = new AddLegalHoldCommand({
Bucket: 'my-protected-bucket',
Key: 'important-document.pdf',
RetentionLegalHoldId: 'legal-case-12345'
});
try {
await client.send(command);
console.log('Legal hold added');
} catch (err) {
console.error('Error adding legal hold:', err);
}
法的保存命令の一覧:
const { ListLegalHoldsCommand } = require('ibm-cos-sdk-v2');
const command = new ListLegalHoldsCommand({
Bucket: 'my-protected-bucket',
Key: 'important-document.pdf'
});
try {
const response = await client.send(command);
console.log('Legal holds listed successfully');
console.log('Legal holds:', JSON.stringify(response.LegalHolds, null, 2));
} catch (err) {
console.error('Error listing legal holds:', err);
}
リーガル・ホールドの削除:
const { DeleteLegalHoldCommand } = require('ibm-cos-sdk-v2');
const command = new DeleteLegalHoldCommand({
Bucket: 'my-protected-bucket',
Key: 'important-document.pdf',
RetentionLegalHoldId: 'legal-case-12345'
});
try {
await client.send(command);
console.log('Legal hold removed');
} catch (err) {
console.error('Error removing legal hold:', err);
}
Key Protect で暗号化されたバケットの作成
IBM Key Protect バケットレベルの暗号化のための暗号鍵管理機能を提供します:
const { CreateBucketCommand } = require('ibm-cos-sdk-v2');
const command = new CreateBucketCommand({
Bucket: 'my-encrypted-bucket',
CreateBucketConfiguration: {
LocationConstraint: 'us-south-standard'
},
IBMSSEKPEncryptionAlgorithm: 'AES256',
IBMSSEKPCustomerRootKeyCrn: 'crn:v1:bluemix:public:kms:us-south:...'
});
try {
await client.send(command);
console.log('Encrypted bucket created');
} catch (err) {
console.error('Error creating encrypted bucket:', err);
}
オブジェクトの名前を変更する
RenameObject IBM のCOS固有のサーバーサイド操作です。 データは転送されず、変更されるのはキーのみです:
const { RenameObjectCommand } = require('ibm-cos-sdk-v2');
const command = new RenameObjectCommand({
Bucket: 'my-bucket',
Key: 'new-object-key', // destination key
RenameSource: 'my-bucket/old-object-key' // source: bucket/key
});
try {
await client.send(command);
console.log('Object renamed successfully');
} catch (err) {
console.error('Error:', err.message);
}
オブジェクトの暗号化の更新
UpdateObjectEncryption 既存のオブジェクトの暗号化キー参照を更新します。 バケットには、 IBM、 Key Protect、またはHPCSのいずれかが設定されている必要があります:
const { UpdateObjectEncryptionCommand } = require('ibm-cos-sdk-v2');
const command = new UpdateObjectEncryptionCommand({
Bucket: 'my-bucket',
Key: 'my-object.txt'
});
try {
await client.send(command);
console.log('Object encryption updated successfully');
} catch (err) {
console.error('Error:', err.message);
}
バケットのレプリケーションの管理
レプリケーション設定の取得:
const { GetBucketReplicationCommand } = require('ibm-cos-sdk-v2');
const command = new GetBucketReplicationCommand({ Bucket: 'my-bucket' });
try {
const response = await client.send(command);
console.log('Bucket replication configuration retrieved successfully');
console.log('Rules:', JSON.stringify(response.ReplicationConfiguration?.Rules, null, 2));
} catch (err) {
console.error('Error:', err.message);
}
レプリケーション設定の削除:
const { DeleteBucketReplicationCommand } = require('ibm-cos-sdk-v2');
const command = new DeleteBucketReplicationCommand({ Bucket: 'my-bucket' });
try {
await client.send(command);
console.log('Bucket replication configuration deleted successfully');
} catch (err) {
console.error('Error:', err.message);
}
レプリケーションの失敗の一覧:
const { ListBucketReplicationFailuresCommand } = require('ibm-cos-sdk-v2');
const command = new ListBucketReplicationFailuresCommand({ Bucket: 'my-bucket' });
try {
const response = await client.send(command);
console.log('Bucket replication failures listed successfully');
console.log('Response:', JSON.stringify(response, null, 2));
} catch (err) {
console.error('Error:', err.message);
}
失敗したレプリケーションの再試行:
const { PutBucketReplicationReattemptCommand } = require('ibm-cos-sdk-v2');
const command = new PutBucketReplicationReattemptCommand({ Bucket: 'my-bucket' });
try {
await client.send(command);
console.log('Bucket replication reattempt triggered successfully');
} catch (err) {
console.error('Error:', err.message);
}
セッションの作成
CreateSession IBM Cloud Object Storage バケットの一時的なセッショントークンを作成します:
const { CreateSessionCommand } = require('ibm-cos-sdk-v2');
const command = new CreateSessionCommand({ Bucket: 'my-bucket' });
try {
const response = await client.send(command);
console.log('Session created successfully');
console.log('Response:', JSON.stringify(response, null, 2));
} catch (err) {
console.error('Error:', err.message);
}
リソースの準備が整うのを待っています
ウェイターは、リソースが所望の状態に達するまでポーリングを行うため、手動によるポーリングループが不要になります。
バケットが存在するのを待つ:
const { waitUntilBucketExists } = require('ibm-cos-sdk-v2');
try {
await waitUntilBucketExists(
{
client: client,
maxWaitTime: 120, // Maximum wait time in seconds
minDelay: 2, // Minimum delay between checks in seconds
maxDelay: 10 // Maximum delay between checks in seconds
},
{ Bucket: 'my-bucket' }
);
console.log('Bucket exists and is ready');
} catch (err) {
console.error('Bucket did not become available:', err);
}
オブジェクトが存在するのを待つ:
const { waitUntilObjectExists } = require('ibm-cos-sdk-v2');
try {
await waitUntilObjectExists(
{
client: client,
maxWaitTime: 60,
minDelay: 1,
maxDelay: 5
},
{
Bucket: 'my-bucket',
Key: 'my-object.txt'
}
);
console.log('Object exists and is ready');
} catch (err) {
console.error('Object did not become available:', err);
}
次のステップ
- 利用可能なすべてのメソッドおよび型に関する詳細については、『 Node.js 』APIリファレンスドキュメント をご確認ください
- その他のサンプルやソースコードについては、「 GitHub 」リポジトリ をご覧ください
- からアップグレードする場合は、 移行ガイド をお読みください。 v1
- サービス固有の機能やベストプラクティスについては、『 IBM Cloud Object Storage 』のドキュメント をご覧ください
- ヘルプおよびサポートについては:
- Stack Overflow で、
ibmなどのタグを付けて質問してください。object-storage - でイシューを作成してください GitHub
- IBM Cloud サポート へのお問い合わせ
- Stack Overflow で、