このページは、お客様の言語ではご利用いただけません。Huawei Cloudは、より多くの言語バージョンを追加するために懸命に取り組んでいます。ご協力ありがとうございました。

Compute
Elastic Cloud Server
Huawei Cloud Flexus
Bare Metal Server
Auto Scaling
Image Management Service
Dedicated Host
FunctionGraph
Cloud Phone Host
Huawei Cloud EulerOS
Networking
Virtual Private Cloud
Elastic IP
Elastic Load Balance
NAT Gateway
Direct Connect
Virtual Private Network
VPC Endpoint
Cloud Connect
Enterprise Router
Enterprise Switch
Global Accelerator
Management & Governance
Cloud Eye
Identity and Access Management
Cloud Trace Service
Resource Formation Service
Tag Management Service
Log Tank Service
Config
OneAccess
Resource Access Manager
Simple Message Notification
Application Performance Management
Application Operations Management
Organizations
Optimization Advisor
IAM Identity Center
Cloud Operations Center
Resource Governance Center
Migration
Server Migration Service
Object Storage Migration Service
Cloud Data Migration
Migration Center
Cloud Ecosystem
KooGallery
Partner Center
User Support
My Account
Billing Center
Cost Center
Resource Center
Enterprise Management
Service Tickets
HUAWEI CLOUD (International) FAQs
ICP Filing
Support Plans
My Credentials
Customer Operation Capabilities
Partner Support Plans
Professional Services
Analytics
MapReduce Service
Data Lake Insight
CloudTable Service
Cloud Search Service
Data Lake Visualization
Data Ingestion Service
GaussDB(DWS)
DataArts Studio
Data Lake Factory
DataArts Lake Formation
IoT
IoT Device Access
Others
Product Pricing Details
System Permissions
Console Quick Start
Common FAQs
Instructions for Associating with a HUAWEI CLOUD Partner
Message Center
Security & Compliance
Security Technologies and Applications
Web Application Firewall
Host Security Service
Cloud Firewall
SecMaster
Anti-DDoS Service
Data Encryption Workshop
Database Security Service
Cloud Bastion Host
Data Security Center
Cloud Certificate Manager
Edge Security
Managed Threat Detection
Blockchain
Blockchain Service
Web3 Node Engine Service
Media Services
Media Processing Center
Video On Demand
Live
SparkRTC
MetaStudio
Storage
Object Storage Service
Elastic Volume Service
Cloud Backup and Recovery
Storage Disaster Recovery Service
Scalable File Service Turbo
Scalable File Service
Volume Backup Service
Cloud Server Backup Service
Data Express Service
Dedicated Distributed Storage Service
Containers
Cloud Container Engine
SoftWare Repository for Container
Application Service Mesh
Ubiquitous Cloud Native Service
Cloud Container Instance
Databases
Relational Database Service
Document Database Service
Data Admin Service
Data Replication Service
GeminiDB
GaussDB
Distributed Database Middleware
Database and Application Migration UGO
TaurusDB
Middleware
Distributed Cache Service
API Gateway
Distributed Message Service for Kafka
Distributed Message Service for RabbitMQ
Distributed Message Service for RocketMQ
Cloud Service Engine
Multi-Site High Availability Service
EventGrid
Dedicated Cloud
Dedicated Computing Cluster
Business Applications
Workspace
ROMA Connect
Message & SMS
Domain Name Service
Edge Data Center Management
Meeting
AI
Face Recognition Service
Graph Engine Service
Content Moderation
Image Recognition
Optical Character Recognition
ModelArts
ImageSearch
Conversational Bot Service
Speech Interaction Service
Huawei HiLens
Video Intelligent Analysis Service
Developer Tools
SDK Developer Guide
API Request Signing Guide
Terraform
Koo Command Line Interface
Content Delivery & Edge Computing
Content Delivery Network
Intelligent EdgeFabric
CloudPond
Intelligent EdgeCloud
Solutions
SAP Cloud
High Performance Computing
Developer Services
ServiceStage
CodeArts
CodeArts PerfTest
CodeArts Req
CodeArts Pipeline
CodeArts Build
CodeArts Deploy
CodeArts Artifact
CodeArts TestPlan
CodeArts Check
CodeArts Repo
Cloud Application Engine
MacroVerse aPaaS
KooMessage
KooPhone
KooDrive
Help Center/ Object Storage Service/ SDK Reference/ Node.js/ Getting Started (SDK for Node.js)/ General Ways to Use ObsClient (SDK for Node.js)

General Ways to Use ObsClient (SDK for Node.js)

Updated on 2024-11-13 GMT+08:00
NOTICE:

If you have any questions during development, post them on the Issues page of GitHub.

Result Returned via a Callback Function

ObsClient returns the results by using a callback function that contains two parameters in sequence: the exception information parameter and the SDK common result object parameter. If the exception information parameter in the callback function is not null, an error occurs during the API calling. Otherwise, the API is called. In such conditions, you need to obtain the HTTP status code from the SDK common result object parameter to check whether the operation is successful. Sample code:

// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

// Construct request parameters for bucket operations.
var requestParam1 = {
       Bucket : 'bucketname'
       // Other fields.
};

var callback1 = (err, result) => {
       // Process the result of a bucket-related API call.
};

// Call the APIs for bucket operations, such as creating a bucket.
obsClient.createBucket(requestParam1, callback1);

// Construct request parameters for object operations.
var requestParam2 = {
       Bucket : 'bucketname',
       Key : 'objectname'
       // Other fields.
};

var callback2 = (err, result) => {
       // Process the result of an object-related API call.
};

// Call an object-related API, such as the API for downloading an object.
obsClient.getObject(requestParam2, callback2);
NOTE:

For APIs used for bucket operations, the Bucket parameter contained in the request object indicates the bucket name. For APIs used for object operations, the Bucket and Key parameters contained in the request object specify the bucket name and object name, respectively.

Sample code:

// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

// Call APIs to perform operations, such as uploading an object. 
obsClient.putObject({
       Bucket : 'bucketname',
       Key : 'objectname',
       Body : 'Hello OBS'
}, (err, result) => {
       // If the err parameter is not null, an error occurs during the API calling.
       if(err){
              console.log('Error-->' + err);
       }else{
              // If the exception information is null, the API call is complete. In such conditions, you need to check the HTTP status code.
              if(result.CommonMsg.Status < 300){// The operation is successful.
                     if(result.InterfaceResult){
                           // Process the business logic after the operation is successful.
                     };
              }else{// The operation fails. Obtain details about the exception.
                     console.log('Code-->' + result.CommonMsg.Code); 
                     console.log('Message-->' + result.CommonMsg.Message);
                     console.log('HostId-->' + result.CommonMsg.HostId);
                     console.log('RequestId-->' + result.CommonMsg.RequestId);
              };
       };
});

Result Returned via the Promise Object

ObsClient supports results returned via the Promise object. If no exception is caught by the catch method of the Promise object, the API calling is complete. In such conditions, you need to obtain the HTTP status code from the SDK Common Result Object to check whether the operation is successful. The following is a code sample:

// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});


// Construct request parameters for bucket operations.
var requestParam1 = {
       Bucket : 'bucketname'
       // Other fields.
};

// Call the APIs for bucket operations, such as creating a bucket.
var promise1 = obsClient.createBucket(requestParam1);
promise1.then((result) => {
   // Process the API call result.
}).catch((err)=>{
   // Rectify the fault.
});

// Construct request parameters for object operations.
var requestParam2 = {
       Bucket : 'bucketname',
       Key : 'objectname'
       // Other fields.
};

// Call an object-related API, such as the API for downloading an object.
var promise2 = obsClient.getObject(requestParam2);
promise2.then((result) => {
   // Process the API call result.
}).catch((err)=>{
   // Rectify the fault.
});
NOTE:

For APIs used for bucket operations, the Bucket parameter contained in the request object indicates the bucket name. For APIs used for object operations, the Bucket and Key parameters contained in the request object specify the bucket name and object name, respectively.

Sample code:

// Import the OBS library.
// Use npm to install the client.
const ObsClient = require("esdk-obs-nodejs");
// Use the source code to install the client.
// var ObsClient = require('./lib/obs');

// Create an instance of ObsClient.
const obsClient = new ObsClient({
  // Obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways. Using hard coding may result in leakage.
  // Obtain an AK/SK pair on the management console. For details, see https://support.huaweicloud.com/intl/en-us/usermanual-ca/ca_01_0003.html.
  access_key_id: process.env.ACCESS_KEY_ID,
  secret_access_key: process.env.SECRET_ACCESS_KEY,
  // (Optional) If you use a temporary AK/SK pair and a security token to access OBS, you are advised not to use hard coding, which may result in information leakage. You can obtain an AK/SK pair using environment variables or import an AK/SK pair in other ways.
  // security_token: process.env.SECURITY_TOKEN,
  // Enter the endpoint corresponding to the region where the bucket is located. CN-Hong Kong is used here as an example. Replace it with the one currently in use.
  server: "https://obs.ap-southeast-1.myhuaweicloud.com"
});

// Call APIs to perform operations, such as uploading an object. 
obsClient.putObject({
       Bucket : 'bucketname',
       Key : 'objectname',
       Body : 'Hello OBS'
}).then((result) => {
    // If no exception occurs and the API call is complete, check the HTTP status code.
    if(result.CommonMsg.Status < 300){// Operation succeeded
        if(result.InterfaceResult){
            // Process the business logic after the operation is successful.
        };
}else{// The operation fails. Obtain details about the exception.
        console.log('Code-->' + result.CommonMsg.Code); 
        console.log('Message-->' + result.CommonMsg.Message);
        console.log('HostId-->' + result.CommonMsg.HostId);
        console.log('RequestId-->' + result.CommonMsg.RequestId);
    };
}).catch((err) => {
    // An exception occurred after the API is called.
    console.error('Error-->' + err);
});

We use cookies to improve our site and your experience. By continuing to browse our site you accept our cookie policy. Find out more

Feedback

Feedback

Feedback

0/500

Selected Content

Submit selected content with the feedback