Aliyun OSS Node.js Client
raw JSON →`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.
Common errors
error Error: NoSuchBucket: The specified bucket does not exist. ↓
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. ↓
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> ↓
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. ↓
-), and must start and end with a letter or number. Warnings
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. ↓
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. ↓
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. ↓
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. ↓
Install
npm install ali-oss yarn add ali-oss pnpm add ali-oss Imports
- OSS wrong
import { OSS } from 'ali-oss'correctimport OSS from 'ali-oss' - OSS (CommonJS) wrong
const { OSS } = require('ali-oss')correctconst OSS = require('ali-oss') - PutObjectOptions
import type { PutObjectOptions } from 'ali-oss'
Quickstart
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();