Aliyun OSS Node.js Client

raw JSON →
6.23.0 verified Sun Apr 19 auth: no javascript

`ali-oss` is the official Node.js client library for Alibaba Cloud Object Storage Service (OSS). It provides a comprehensive, promise-based API for interacting with OSS buckets and objects, covering essential operations like uploading, downloading, listing, and managing object access. The current stable version is `6.23.0`, released on May 15, 2025. The library maintains a regular release cadence, with minor versions frequently introducing new features, bug fixes, and performance enhancements. Key differentiators include direct support for Alibaba Cloud-specific features such as CloudBox, V4 signatures, and detailed bucket/object lifecycle management, making it an essential tool for applications integrating with Alibaba Cloud infrastructure. It supports Node.js environments from version 8 and above, and also offers limited browser compatibility for certain operations.

error Error: NoSuchBucket: The specified bucket does not exist.
cause The configured bucket name in the client or for the operation does not exist, is misspelled, or the `region` configured for the client does not match the bucket's actual region.
fix
Verify the bucket name for typos and confirm the region in your OSS client configuration precisely matches the actual region where your bucket is located. Confirm the bucket exists and is accessible in your Alibaba Cloud console.
error Error: AccessDenied: You have no right to access this object because of bucket acl.
cause The `accessKeyId` and `accessKeySecret` provided do not have sufficient permissions (either via IAM policy attached to the user or a bucket ACL/policy) to perform the requested operation on the specified resource.
fix
Review the IAM user's policies linked to your accessKeyId or the bucket's ACLs and policies. Grant the necessary oss:PutObject, oss:GetObject, oss:DeleteObject, etc., permissions for the bucket and objects involved in your operations.
error Error: RequestError: connect ECONNREFUSED <IP_ADDRESS>:<PORT>
cause The client could not establish a network connection to the OSS endpoint. This is commonly caused by an incorrect `region` (leading to a wrong endpoint), network connectivity issues (e.g., firewall, proxy settings), or DNS resolution problems.
fix
Ensure the region in your client configuration is accurate (e.g., oss-cn-hangzhou). Check your local network, proxy settings, and firewall rules to ensure outbound connections to the OSS endpoint are allowed. Verify DNS resolution for the OSS domain for your region.
error Error: The bucket name 'Invalid-Bucket!' is invalid.
cause The bucket name provided to the `ali-oss` client or in an operation violates Alibaba Cloud OSS naming conventions. This can include using uppercase letters, underscores, or certain special characters.
fix
Rename your bucket to comply with OSS naming rules: bucket names must be 3 to 63 characters long, consist only of lowercase letters, numbers, and hyphens (-), and must start and end with a letter or number.
breaking As of v6.19.0, object name verification for signed URLs became stricter and is enabled by default. If your application generates signed URLs with non-standard object names (e.g., containing characters that previously worked but are invalid by OSS naming rules), these URLs might now be rejected by OSS.
fix Review your object naming conventions and ensure they strictly comply with Alibaba Cloud OSS object naming rules. If encountering issues, consult OSS documentation for valid object name characters. While possible to disable strict verification, it's not recommended for security reasons.
gotcha When uploading large files (generally over 100MB), using `client.put` directly can be inefficient, prone to failure due to network issues, or lead to excessive memory usage. The `multipartUpload` method is designed for robust and resumable large file uploads.
fix For files exceeding a few megabytes, always use `client.multipartUpload(objectName, filePath, options)` to leverage chunking, parallel uploads, and resumable transfer capabilities for better performance and reliability.
gotcha The client added support for Signature V4 in v6.20.0, and support for CloudBox in v6.23.0. While older signature versions or access methods might still function, using the latest V4 signature offers enhanced security, and CloudBox-specific operations require proper configuration.
fix For new deployments and enhanced security, ensure your OSS client and bucket configuration (if applicable) are set to utilize Signature V4. For CloudBox access, configure the `endpoint` and `authorizationV4: true` option as specified in the documentation.
gotcha Connecting to OSS fundamentally requires correct `region`, `accessKeyId`, and `accessKeySecret`. Incorrectly configured credentials, an invalid `region` parameter, or a non-existent `bucket` in the specified region will lead to authentication failures or 'NoSuchBucket' errors, preventing any operations.
fix Thoroughly double-check your `region` (e.g., 'oss-cn-hangzhou'), `accessKeyId`, and `accessKeySecret` against your Alibaba Cloud console. Ensure the IAM user associated with the `accessKeyId` has the necessary permissions for the bucket and intended operations. Verify the bucket exists in the specified region.
npm install ali-oss
yarn add ali-oss
pnpm add ali-oss

This quickstart demonstrates basic `ali-oss` operations: client initialization, uploading a local file, downloading it, listing objects in a bucket, retrieving object metadata, and finally deleting the uploaded file. It uses environment variables for secure credential handling.

import OSS from 'ali-oss';
import { readFileSync, unlinkSync, existsSync, writeFileSync } from 'fs';
import { join } from 'path';

async function runOssOperations() {
  const client = new OSS({
    region: process.env.ALI_OSS_REGION ?? 'oss-cn-hangzhou', // e.g., 'oss-cn-hangzhou'
    accessKeyId: process.env.ALI_OSS_AKID ?? 'YOUR_ACCESS_KEY_ID',
    accessKeySecret: process.env.ALI_OSS_AKSECRET ?? 'YOUR_ACCESS_KEY_SECRET',
    bucket: process.env.ALI_OSS_BUCKET ?? 'your-test-bucket', // Ensure this bucket exists
    secure: true, // Always use HTTPS for production
  });

  const objectName = `my-test-file-${Date.now()}.txt`;
  const localFilePath = join(process.cwd(), 'temp_test_file.txt');
  const fileContent = 'Hello, Alibaba Cloud OSS! This is a test file.\nAnother line of content.';

  // Create a dummy local file for upload
  writeFileSync(localFilePath, fileContent);
  console.log(`Created local file: ${localFilePath}`);

  try {
    // 1. Upload a file
    console.log(`Uploading ${objectName}...`);
    const putResult = await client.put(objectName, localFilePath);
    console.log('Upload successful. ETag:', putResult.etag, 'Status:', putResult.res.status);

    // 2. Download the file and verify content
    console.log(`Downloading ${objectName}...`);
    const getResult = await client.get(objectName);
    console.log('Download successful. Content:', getResult.content.toString());
    if (getResult.content.toString() === fileContent) {
      console.log('Content verification successful.');
    } else {
      console.warn('Downloaded content differs from original.');
    }

    // 3. List objects in the bucket
    console.log('Listing objects in bucket...');
    const listResult = await client.list({
      prefix: 'my-test-file-', // Filter for our test files
      'max-keys': 5,
    });
    console.log('Found objects:', listResult.objects.map(obj => obj.name));

    // 4. Get object metadata (head request)
    console.log(`Getting metadata for ${objectName}...`);
    const headResult = await client.head(objectName);
    console.log('Object metadata status:', headResult.res.status, 'Content-Length:', headResult.res.headers['content-length']);

    // 5. Delete the file
    console.log(`Deleting ${objectName}...`);
    const deleteResult = await client.delete(objectName);
    console.log('Delete successful. Status:', deleteResult.res.status);

  } catch (error: any) {
    console.error('OSS operation failed:', error.message);
    if (error.code === 'NoSuchBucket') {
      console.error('ERROR: Please ensure the bucket exists and you have correct region and permissions.');
    } else if (error.code === 'AccessDenied') {
      console.error('ERROR: Check your AccessKeyId, AccessKeySecret, and IAM permissions.');
    }
  } finally {
    // Clean up local file
    if (existsSync(localFilePath)) {
      unlinkSync(localFilePath);
      console.log(`Cleaned up local file: ${localFilePath}`);
    }
  }
}

runOssOperations();