Node.js - Getting Started with Alibaba Cloud OSSThere are some options if you need cloud service for storing files. Besides Amazon AWS S3 and Google Cloud Storage, chinese Internet giant Alibaba also offers similar service named OSS (Object Storage Service). Just like other similar services, they provide API for managing objects. Therefore, we can use the API to integrate OSS with our application. In this tutorial, I'm going to show you the basic preparation of how to use Alibaba OSS on your Node.js application and also code examples.

1. Register for an Alibaba Cloud Account

The first thing you need to do is registering for an Alibaba Account. Open Alibaba Cloud registration page. First, you need to select your country, enter your email and a new password. Then a confirmation code will be sent to your email. Check your email and paste the code on the provided box.

Once you've successfully confirmed your email, you'll be asked to enter billing information and add payment method. After that, you can create a new instance. If you get a free trial, you can use it. Search for Object Storage Servie and click on Try Now

For managing OSS, you can go the OSS console. There, you can create a bucket, upload some files, edit ACL, etc.

Alibaba OSS Console

2. Create AccessKey

Your application need to get authenticated for accessing OSS. As for authentiation, it requires client id along with valid client secret. To create a new access key, open Access Key Management page of Alibaba Cloud. On that page, click on Create Access Key and a new one will be generated instantly. The user access key must be downloaded immediately by clicking on Save AccessKey information. In case you have already closed it, just delete the generated access key and create a new one.

Alibaba Cloud Access Key Security Management

3. Code

After getting the information for authentication, we can start to code. To make it easy, we use a node module named ali-oss. Add it on the package.json

  "ali-oss": "~6.0.0"

Beforehand, copy the client id and client secret on the downloaded file to your .env

  ALIBABA_CLOUD_ACCESS_KEY_ID=abcdeabcdeabcde
  ALIBABA_CLOUD_ACCESS_KEY_SECRET=abcdeabcdeabcdeabcdeabcdeabcde

That means you've to load the .env file first somewhere before those value used. You can use dotenv or other similar modules.

In this tutorial, I only show the basic usages which include list buckets, list objects, upload object, and download object.

First we create a helper and here is the constructor

helpers/alibaba-oss.js

  const _ = require('lodash');
  const OSS = require('ali-oss');
  const fs = require('fs');
  
  function AliOssClient({ bucket, region }) {
    if (!(this instanceof AliOssClient)) {
      return new AliOssClient();
    }
  
    this.client = new OSS({
      accessKeyId: process.env.ALIBABA_CLOUD_ACCESS_KEY_ID,
      accessKeySecret: process.env.ALIBABA_CLOUD_ACCESS_KEY_SECRET,
      bucket,
region, }); }

example.js

  const OssClient = require('./helpers/alibaba-oss');

  const ossClient = new OssClient({ bucket: 'your-bucket-name', region: 'your-bucket-region (e.g. "oss-us-west-1")' });

Get The List of Buckets

To get the list of buckets use client.listBuckets with query as the first parameter and options as the second parameter.

  /**
   * List all buckets in your account.
   * @param {Object} [query]
   * @param {String} [query.prefix] - Search objects that match prefix
   * @param {String} [query.marker] - Search start from marker, including marker
   * @param {String|Number} [query['max-keys'], Maximum objects in result
   * @param {Object} [options] - Optional params
   * @param {Number} [options.timeout] - Request timeout
   * @return {Promise}
   */
  AliOssClient.prototype.listBuckets = async function (query, options) {
    const result = await this.client.listBuckets(query, options);
    console.log('Bucket names: ' + _.map(result.buckets, 'name'));
  
    return result;
  };

example.js

  ossClient.listBuckets();

Get The List of Objects

To get the list of objects on your bucket, use client.list with query as the first parameter and options as the second parameter.

helpers/alibaba-oss.js

  /**
   * List all buckets in your account.
   * @param {Object} [query]
   * @param {String} [query.prefix] - Search objects that match prefix
   * @param {String} [query.marker] - Search start from marker, including marker
   * @param {String|Number} [query['max-keys'], Maximum objects in result
   * @param {Object} [options] - Optional params
   * @param {Number} [options.timeout] - Request timeout
   * @return {Promise}
   */
  AliOssClient.prototype.listObjects = async function (query, options) {
    const result = await this.client.list(query, options);
  
    console.log('Object names: ' + _.map(result.objects, 'name'));
  
    return result;
  };

example.js

  ossClient.listObjects();

Upload An Object

For uploading an object, use client.put with object key as the first parameter and the file to upload as the second parameter. You can read this post for advanced upload tutorial.

helpers/alibaba-oss.js

  /**
   * Upload an object to OSS.
   * @param {String} objectKey - Object name in OSS
   * @param {String} file - Path to local file, buffer, or ReadStream content instance
   * @param {Object} [options] - Optional params
   * @param {Number} [options.timeout] - Request timeout
   * @param {String} [options.mime] - Custom mime
   * @param {Object} [options.meta] - user meta, will send with x-oss-meta- prefix string e.g.: { uid: 111, pid: 222 }
   * @param {Object} [options.callback] - Callback parameter
   * @param {String} options.callback.url - After file uploaded, OSS will send callback to this URL.
   * @param {String} [options.callback.host] - Host header for callback request.
   * @param {String} options.callback.body - Request body for callback request. e.g.: key=$(key)&etag=$(etag)&my_var=$(x:my_var)
   * @param {String} [options.callback.contentType] - Content-Type of the callback requests initiatiated,
   * either application/x-www-form-urlencoded (default) or application/json
   * @param {String} [options.callback.customValue] - Map of key-values. e.g.: { var1: 'value1' }
   * @param {Object} [options.headers] - See RFC2616
   * @return {Promise}
   */
  AliOssClient.prototype.uploadObject = async function (objectKey, file, options) {
    return await this.client.put(objectKey, file, options);
  };

example.js

 ossClient.uploadObject('key-name', '/path/to/local-file');

Download An Object

For downloading an object, use client.get with object key as the first parameter and downloaded file as the second parameter.

helpers/alibaba-oss.js

  /**
   * Upload an object to OSS.
   * @param {String} objectKey - Object name in OSS
   * @param {String} file - Path to local file, buffer, or ReadStream content instance
   * @param {Object} [options] - Optional params
   * @param {Number} [options.timeout] - Request timeout
   * @param {String} [options.mime] - Custom mime
   * @param {Object} [options.meta] - user meta, will send with x-oss-meta- prefix string e.g.: { uid: 111, pid: 222 }
   * @param {Object} [options.callback] - Callback parameter
   * @param {Object} [options.headers] - See RFC 2616
   * @return {Promise}
   */
  AliOssClient.prototype.downloadObject = async function (objectKey, file, options) {
    return await this.client.get(objectKey, file, options);
  };

example.js

  ossClient.downloadObject('key-name', '/path/to/local-file');

That's all for this tutorial. Thanks for reading.