All Products
Search
Document Center

Object Storage Service:Install OSS SDK for Node.js

Last Updated:May 23, 2024

If you want to manage Object Storage Service (OSS) buckets, upload and download objects, manage data, and perform image processing (IMG), install OSS SDK for Node.js first. This topic describes how to install and use OSS SDK for Node.js.

Prerequisites

  • OSS is activated.

  • The AccessKey pair of a RAM user is created. An AccessKey pair consists of an AccessKey ID and an AccessKey secret.

    The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using the AccessKey pair to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. If you deploy your service on a server, you can use a RAM user or Security Token Service (STS) credentials to call API operations or perform routine operations. If you deploy your service on a client, use STS credentials to call API operations. For more information, see

    Resource Access Management.

Background information

OSS SDK for Node.js is built based on the Node.js environment.

The sample project in the official document is based on OSS SDK for Node.js 6.X. If you are using an earlier version, see OSS SDK for Node.js documentation. To upgrade OSS SDK for Node.js to version 6.X, see Upgrading Notes (5.x to 6.x).

For more information about the source code of OSS SDK for Node.js, visit GitHub. For more information about code examples, see API documentation.

Install OSS SDK for Node.js

OSS supports Node.js 8.0.0 and later. To use OSS SDK for Node.js in versions of Node.js earlier than 8.0.0, use OSS SDK for Node.js V4.x.

Run the npm install ali-oss --save command to install the SDK package. For more information, visit npm.

Use OSS SDK for Node.js

OSS SDK for Node.js supports Promise-based asynchronous programming. You can use async/await or then/catch to process Promise objects.

async/await

You can use the async and await keywords to write code that is similar to synchronous code. The keywords process Promise objects and make asynchronous code clearer. The following sample code provides an example on how to upload and download objects by using the async/await syntax.

const OSS = require('ali-oss');

// Initialize an OSSClient instance. Replace the following parameters with your actual configuration information: 
const client = new OSS({
  region: 'yourregion', // Specify the region in which the bucket is located. Example: 'oss-cn-hangzhou'. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID, // Make sure that the OSS_ACCESS_KEY_ID environment variable is configured. 
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, // Make sure that the OSS_ACCESS_KEY_SECRET environment variable is configured. 
  bucket: 'yourbucketname', // Specify the name of the bucket. Example: 'my-bucket-name'. 
});

async function uploadAndDownloadFile() {
  try {
    // Upload an object to OSS. Replace 'object' with the name of the object in OSS. Replace 'localfile' with the path of the local file that you want to upload. 
    const uploadResult = await client.put('object', 'localfile');
    console.log('Upload succeeded:', uploadResult);
    // Download the object from OSS to verify that the upload was successful. 
    const getResult = await client.get('object');
    console.log('Object downloaded:', getResult);
  } catch (error) {
    console.error('Error:', error);
    // Write your error handling code here. 
  }
}

uploadAndDownloadFile();

then/catch

You can use the then method of the Promise object to process a successful synchronous operation and the catch method to handle errors. The following sample code provides an example on how to upload and download an object by using then/catch:

const OSS = require('ali-oss');

// Initialize an OSSClient instance. Replace the following parameters with your actual configuration information: 
const client = new OSS({
  region: 'yourregion', // Specify the region in which the bucket is located. Example: 'oss-cn-hangzhou'. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID, // Make sure that the OSS_ACCESS_KEY_ID environment variable is configured. 
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET, // Make sure that the OSS_ACCESS_KEY_SECRET environment variable is configured. 
  bucket: 'yourbucketname', // Specify the name of the bucket. Example: 'my-bucket-name'. 
});

// Use the PUT method to upload an object to OSS and use then() in a chained manner to process the result or handle an error. 
client.put('object', 'localfile')
  .then((uploadResult) => {
    console.log('Upload succeeded:', uploadResult);
    // Download the object to verify that the upload was successful. 
    return client.get('object');
  })
  .then((getResult) => {
    console.log('Object downloaded:', getResult);
  })
  .catch((error) => {
    console.error('Error:', error);
    // Write your error handling code here. 
  });