Each OSS object consists of a key, data, and metadata. Object metadata falls into two categories:
Standard HTTP headers: System-managed fields such as
Content-Type,Cache-Control, andContent-Dispositionthat control caching behavior, forced download behavior, and other HTTP response policies.User-defined metadata: Arbitrary key-value pairs you attach to an object to store information about its purpose or properties. These values are for your own use and do not affect how OSS handles the object.
This page covers three operations: setting metadata during upload, updating metadata on an existing object, and retrieving metadata.
Prerequisites
Before you begin, ensure that you have:
Installed the
ali-ossNode.js SDKSet the
OSS_ACCESS_KEY_IDandOSS_ACCESS_KEY_SECRETenvironment variables with your access credentialsAn existing OSS bucket
Set metadata during upload
Pass a meta object in the options parameter of put, putStream, or multipartUpload to attach user-defined metadata at upload time.
All metadata values must be strings.
const OSS = require('ali-oss');
const path = require('path');
const client = new OSS({
// Read credentials from environment variables
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
region: 'oss-cn-hangzhou',
authorizationV4: true,
bucket: 'yourBucketName',
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
});
async function put() {
try {
let result = await client.put('object-name', path.normalize('D:\\localpath\\examplefile.txt'), {
meta: {
year: '2025', // Values must be strings
people: 'mary'
}
});
console.log(result);
} catch (e) {
console.log(e);
}
}
put();Update object metadata
Use putMeta to replace the metadata of an existing object.
const OSS = require('ali-oss');
const client = new OSS({
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
region: 'oss-cn-hangzhou',
authorizationV4: true,
bucket: 'yourBucketName',
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
});
async function putMeta() {
try {
let meta = { year: 2025, people: 'jack' };
let result = await client.putMeta('object-name', meta);
console.log(result);
} catch (e) {
console.log(e);
}
}
putMeta();Get object metadata
Use head to retrieve object metadata.
const OSS = require('ali-oss');
const client = new OSS({
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
region: 'oss-cn-hangzhou',
authorizationV4: true,
bucket: 'yourBucketName',
endpoint: 'https://oss-cn-hangzhou.aliyuncs.com',
});
async function headInfo() {
// Specify the full object path, excluding the bucket name
const result = await client.head('exampledir/exampleobject.txt');
console.log(result);
}
headInfo();