All Products
Search
Document Center

Object Storage Service:Use OSS SDK for Node.js to manage object metadata

Last Updated:May 29, 2024

Objects that are stored in Object Storage Service (OSS) consist of keys, data, and metadata. Object metadata describes object attributes. Object metadata includes standard HTTP headers and user metadata. You can create custom HTTP request policies such as object cache policies and forced object download policies by configuring standard HTTP headers. You can configure user metadata for an object to identify the purposes or attributes of the object.

Specify object metadata when you upload an object

When you call put, putStream, or multipartUpload, you can configure the meta parameter to specify the object metadata.

const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
});

async function put() {
  try {
    let meta = { year: 2016, people: 'mary' };
    let result = await client.put('object-name', path.normalize('D:\\localpath\\examplefile.txt'), meta);
  console.log(result);
  } catch (e) {
    console.log(e);
  }
}

put();

Modify existing object metadata

You can call putMeta to modify the metadata of an existing object.

const OSS = require('ali-oss');

const client = new OSS({
  // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou. 
  region: 'yourRegion',
  // Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the bucket. 
  bucket: 'examplebucket'
});

async function putMeta() {
  try {
    let meta = { year: 2023, people: 'mary' };
    let result = await client.putMeta('object-name', meta);
    console.log(result);
  } catch (e) {
    console.log(e);
  }
}

putMeta();