All Products
Search
Document Center

Object Storage Service:Check if an object exists (Node.js SDK)

Last Updated:Nov 29, 2025

You can check whether an object exists in a bucket before you perform an operation on it.

The following code shows how to check whether an object exists:

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

const client = new OSS({
  // Set yourregion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run this code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  authorizationV4: true,
  // Set yourBucketName to the name of your bucket.
  bucket: 'yourBucketName',
});

async function isExistObject(name, options = {}) {
  try {
      await client.head(name, options);
      console.log('The object exists.')
   }  catch (error) {
      if (error.code === 'NoSuchKey') {
        console.log('The object does not exist.')
      }
   }
}
// Check if an object exists in a bucket for which versioning is disabled.
// Set yourObjectName to the full path of the object. The path cannot include the bucket name. For example, example/test.txt.
const name = 'yourObjectName'
isExistObject(name)

// Check if an object with a specified version ID exists in a versioning-enabled bucket.
const options = {
    // Set YourObjectVersionId to the version ID of the object.
    versionId: 'YourObjectVersionId' 
}
isExistObject(name, options)