{"id":12792,"library":"ali-oss","title":"Aliyun OSS Node.js Client","description":"`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.","status":"active","version":"6.23.0","language":"javascript","source_language":"en","source_url":"https://github.com/ali-sdk/ali-oss","tags":["javascript","oss","client","file","aliyun"],"install":[{"cmd":"npm install ali-oss","lang":"bash","label":"npm"},{"cmd":"yarn add ali-oss","lang":"bash","label":"yarn"},{"cmd":"pnpm add ali-oss","lang":"bash","label":"pnpm"}],"dependencies":[],"imports":[{"note":"The primary client class is a default export for ESM. Using named import will result in an undefined `OSS`.","wrong":"import { OSS } from 'ali-oss'","symbol":"OSS","correct":"import OSS from 'ali-oss'"},{"note":"For CommonJS modules, the client class is the module's default export. Destructuring will not work as expected.","wrong":"const { OSS } = require('ali-oss')","symbol":"OSS (CommonJS)","correct":"const OSS = require('ali-oss')"},{"note":"TypeScript users can import various interfaces and types, such as `PutObjectOptions` for method parameters or `ListObjectResult` for return types, to enhance type safety.","symbol":"PutObjectOptions","correct":"import type { PutObjectOptions } from 'ali-oss'"}],"quickstart":{"code":"import OSS from 'ali-oss';\nimport { readFileSync, unlinkSync, existsSync, writeFileSync } from 'fs';\nimport { join } from 'path';\n\nasync function runOssOperations() {\n  const client = new OSS({\n    region: process.env.ALI_OSS_REGION ?? 'oss-cn-hangzhou', // e.g., 'oss-cn-hangzhou'\n    accessKeyId: process.env.ALI_OSS_AKID ?? 'YOUR_ACCESS_KEY_ID',\n    accessKeySecret: process.env.ALI_OSS_AKSECRET ?? 'YOUR_ACCESS_KEY_SECRET',\n    bucket: process.env.ALI_OSS_BUCKET ?? 'your-test-bucket', // Ensure this bucket exists\n    secure: true, // Always use HTTPS for production\n  });\n\n  const objectName = `my-test-file-${Date.now()}.txt`;\n  const localFilePath = join(process.cwd(), 'temp_test_file.txt');\n  const fileContent = 'Hello, Alibaba Cloud OSS! This is a test file.\\nAnother line of content.';\n\n  // Create a dummy local file for upload\n  writeFileSync(localFilePath, fileContent);\n  console.log(`Created local file: ${localFilePath}`);\n\n  try {\n    // 1. Upload a file\n    console.log(`Uploading ${objectName}...`);\n    const putResult = await client.put(objectName, localFilePath);\n    console.log('Upload successful. ETag:', putResult.etag, 'Status:', putResult.res.status);\n\n    // 2. Download the file and verify content\n    console.log(`Downloading ${objectName}...`);\n    const getResult = await client.get(objectName);\n    console.log('Download successful. Content:', getResult.content.toString());\n    if (getResult.content.toString() === fileContent) {\n      console.log('Content verification successful.');\n    } else {\n      console.warn('Downloaded content differs from original.');\n    }\n\n    // 3. List objects in the bucket\n    console.log('Listing objects in bucket...');\n    const listResult = await client.list({\n      prefix: 'my-test-file-', // Filter for our test files\n      'max-keys': 5,\n    });\n    console.log('Found objects:', listResult.objects.map(obj => obj.name));\n\n    // 4. Get object metadata (head request)\n    console.log(`Getting metadata for ${objectName}...`);\n    const headResult = await client.head(objectName);\n    console.log('Object metadata status:', headResult.res.status, 'Content-Length:', headResult.res.headers['content-length']);\n\n    // 5. Delete the file\n    console.log(`Deleting ${objectName}...`);\n    const deleteResult = await client.delete(objectName);\n    console.log('Delete successful. Status:', deleteResult.res.status);\n\n  } catch (error: any) {\n    console.error('OSS operation failed:', error.message);\n    if (error.code === 'NoSuchBucket') {\n      console.error('ERROR: Please ensure the bucket exists and you have correct region and permissions.');\n    } else if (error.code === 'AccessDenied') {\n      console.error('ERROR: Check your AccessKeyId, AccessKeySecret, and IAM permissions.');\n    }\n  } finally {\n    // Clean up local file\n    if (existsSync(localFilePath)) {\n      unlinkSync(localFilePath);\n      console.log(`Cleaned up local file: ${localFilePath}`);\n    }\n  }\n}\n\nrunOssOperations();","lang":"typescript","description":"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."},"warnings":[{"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.","message":"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.","severity":"breaking","affected_versions":">=6.19.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=6.0.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=6.20.0"},{"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.","message":"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.","severity":"gotcha","affected_versions":">=6.0.0"}],"env_vars":null,"last_verified":"2026-04-19T00:00:00.000Z","next_check":"2026-07-18T00:00:00.000Z","problems":[{"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.","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.","error":"Error: NoSuchBucket: The specified bucket does not exist."},{"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.","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.","error":"Error: AccessDenied: You have no right to access this object because of bucket acl."},{"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.","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.","error":"Error: RequestError: connect ECONNREFUSED <IP_ADDRESS>:<PORT>"},{"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.","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.","error":"Error: The bucket name 'Invalid-Bucket!' is invalid."}],"ecosystem":"npm","meta_description":null,"install_score":null,"install_tag":null,"quickstart_score":null,"quickstart_tag":null,"pypi_latest":null}