Nafis Islam
Nafis Islam

Reputation: 1509

Check if a blob exist in a path in NodeJS

lets say i want to upload a blob in a container-> azureblob

path: 123/human/a.json

i want to check if any blob exist in path: 123/human/

i couldn't find any good resource for this.

Found this in c# How to check wether a CloudBlobDirectory exists or not?

couldn't find anything on node

Upvotes: 3

Views: 5868

Answers (2)

Mohit Gupta
Mohit Gupta

Reputation: 1

Since doesBlobExist returns a Promise, you can try following implementation:

**

export async function doesBlobExist(
  connectionString,
  containerName,
  blobFileName
): Promise<boolean> {
  const promise: Promise<boolean> = new Promise((resolve, reject) => {
    try {
      const blobService = azure.createBlobService(connectionString);
      
      blobService.doesBlobExist(containerName, blobFileName, function (
        error,
        result
      ) {
        if (!error) {
          resolve(result.exists);
        } else {
          reject(error);
        }
      });
    } catch (err) {
      reject(new Error(err));
    }
  });
  return promise;
}

**

Upvotes: 0

Gaurav Mantri
Gaurav Mantri

Reputation: 136286

If all you want to do is check the existence of any blob in a virtual directory, you can use listBlobsSegmentedWithPrefix method in SDK and try to list the blobs. If the count of results you get is more than zero, that means blobs are present in the directory. For example, take a look at the sample code:

blobService.listBlobsSegmentedWithPrefix('azureblob', '123/human/', null, {
  delimiter: '',
  maxReults: 1
}, function(error, result) {
  if (!error) {
    const entries = result.entries;
    if (entries.length > 0) {
      console.log('Blobs exist in directory...');
    } else {
      console.log('No blobs exist in directory...');
    }
  }
});

If you're looking for existence of a specific blob in a virtual directory, you can simply use doesBlobExist method of the SDK. For example, take a look at the sample code:

blobService.doesBlobExist('azureblob', '123/human/a.json', function(error, result) {
  if (!error) {
    if (result.exists) {
      console.log('Blob exists...');
    } else {
      console.log('Blob does not exist...');
    }
  }
});

Upvotes: 4

Related Questions