All Products
Search
Document Center

Object Storage Service:Get started with OSS SDK for Node.js

Last Updated:Oct 24, 2023

This topic describes how to manage Object Storage Service (OSS) in the Node.js environment, such as listing buckets and uploading objects.

Prerequisites

OSS SDK for Node.js is initialized. For more information, see Initialization.

List buckets

The following code provides an example on how to list buckets that belong to the current Alibaba Cloud account:

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

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET
});

async function listBuckets() {
  try {
    // List all buckets in all regions within the current Alibaba Cloud account. 
    const result = await client.listBuckets();
    console.log(result);
  } catch (err) {
    console.log(err);
  }
}

listBuckets();

Query objects in a bucket

The following code provides an example on how to query objects in a bucket:

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

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'yourbucketname'
});

async function list () {
    // By default, if no parameter is specified, up to 100 objects can be returned. 
    const result = await client.list();
    console.log(result);
}

list();

Upload a local file

The following code provides an example on how to upload a local file to an OSS bucket:

const OSS = require('ali-oss')
const path=require("path")

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket',
});

// Add custom request headers.
const headers = {
  // Specify the storage class of the object. 
  'x-oss-storage-class': 'Standard',
  // Specify the access control list (ACL) of the object. 
  'x-oss-object-acl': 'private',
  // When you access an object by using the URL of the object, specify that the object is downloaded as an attachment. In this example, the name of the downloaded object is example.jpg. 
  'Content-Disposition': 'attachment; filename="example.txt"',
  // Specify tags for the object. You can specify multiple tags for the object at the same time. 
  'x-oss-tagging': 'Tag1=1&Tag2=2',
  // Specify whether the PutObject operation overwrites an object that has the same name. In this example, the x-oss-forbid-overwrite parameter is set to true, which specifies that an existing object that has the same name cannot be overwritten by the uploaded object. 
  'x-oss-forbid-overwrite': 'true',
};

async function put () {
  try {
    // Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object. 
    // If the path of the local file is not specified, the local file is uploaded from the path of the project to which the sample program belongs. 
    const result = await client.put('exampleobject.txt', path.normalize('D:\\localpath\\examplefile.txt')
    // Specify custom headers.
    ,{headers}
    );
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

put();

Download an object

The following code provides an example on how to download an object:

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

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
});

async function get () {
  try {
    // Specify the full paths of the object and the local file. Do not include the bucket name in the full path of the object. 
    // If a file that has the same name already exists, the downloaded object overwrites the file. Otherwise, the downloaded object is saved as a local file. 
    // If you do not specify a path for the downloaded object, the downloaded object is saved to the path of the project to which the sample program belongs. 
    const result = await client.get('exampleobject.txt', 'D:\\localpath\\examplefile.txt');
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

get(); 

Delete an object

The following code provides an example on how to delete an object:

const OSS = require('ali-oss')

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials 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. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Specify the name of the bucket. 
  bucket: 'examplebucket',
});

async function deleteObject () {
  try {
    // Specify the full path of the object. Do not include the bucket name in the full path. 
    let result = await client.delete('exampleobject.txt');
    console.log(result);
  } catch (error) {
    console.log(error);
  }
}

deleteObject();

References

  • List buckets

    • For the complete sample code that is used to list buckets, visit GitHub.

    • For more information about the API operation that you can call to list buckets, see ListBuckets (GetService).

  • Query objects in a bucket

    • For the complete sample code that is used to query objects in a bucket, visit GitHub.

    • For more information about the API operation that you can call to query objects in a bucket, see GetBucket (ListObjects).

  • Upload a local file

    • For the complete sample code that is used to upload a local file, visit GitHub.

    • For more information about the API operation that you can call to upload a local file, see PutObject.

  • Download an object

    • For the complete sample code that is used to download an object, visit GitHub.

    • For more information about the API operation that you can call to download an object, see GetObject.

  • Delete an object

    • For the complete sample code that is used to delete an object, visit GitHub.

    • For more information about the API operation that you can call to delete an object, see DeleteObject.