All Products
Document Center

Object Storage Service:Determine whether an object exists

Last Updated:Oct 18, 2023

Before you perform an operation on an object in a bucket, you must determine whether the object exists. This topic describes how to determine whether an object exists.

The following sample code provides an example on how to determine whether an object exists:

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 you have configured environment variables OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET. 
  accessKeyId: process.env.OSS_ACCESS_KEY_ID,
  accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
  // Specify the name of the 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.')
// Determine whether an object exists in an unversioned bucket. 
// Specify the full path of the object. Do not include the bucket name in the full path. Example: example/test.txt. 
const name = 'yourObjectName'

// Determine whether an object with a specified version ID exists in a versioned bucket. 
const options = {
    // Specify the version ID of the object. 
    versionId: 'YourObjectVersionId' 
isExistObject(name, options)