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 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',
  // The AccessKey pair of an Alibaba Cloud account has permissions on all API operations. Using these credentials to perform operations in OSS is a high-risk operation. We recommend that you use a RAM user to call API operations or perform routine O&M. To create a RAM user, log on to the RAM console. 
  accessKeyId: 'yourAccessKeyId',
  accessKeySecret: 'yourAccessKeySecret',
  // Set yourBucketName to 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. 
// <yourObjectName> indicates the complete path of the object excluding the bucket name. Example: example/test.txt 
const name = 'yourObjectName'

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