0

I'm trying to create a google bucket if it does not exist with the following logic:

async function createBucket(id){
    const bucket = storage.bucket("bucket-" + id);
    const exists = await bucket.exists();
    if (!exists) {
      console.log("creating bucket>>" + "bucket-" + id);
      try {
        await bucket.create();
      } catch (e) {
        console.error("error in creating bucket>>>", e);
      }
    } else {
      console.log("it already exists >>" + exists);
    }
}

strangely, I'm seeing it already exists >> false, when I should only see either it already exists >> true or creating bucket>>bucket-123. Any help with resolving this would be much appreciated. Thank you!

3
  • how storage is initialised? Why not use promise bucket.exits.then(... Commented Apr 26, 2021 at 5:07
  • This is likely subject to race conditions. Commented Apr 26, 2021 at 5:15
  • Is storage.bucket("bucket-" + id); an asynchronous call too? What happens if you write await storage.bucket("bucket-" + id);? Commented Apr 26, 2021 at 5:20

1 Answer 1

2

The issue was that bucket.exists returns an array with the result. In my case, [false], which didn't seem to be suggested at here https://googleapis.dev/nodejs/storage/latest/Bucket.html#exists . The following fixes the issue:

async function createBucket(id){
    const bucket = storage.bucket("bucket-" + id);
    const [exists] = await bucket.exists();
    if (!exists) {
      console.log("creating bucket>>" + "bucket-" + id);
      try {
        await bucket.create();
      } catch (e) {
        console.error("error in creating bucket>>>", e);
      }
    } else {
      console.log("it already exists >>" + exists);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for this, just tried in google cloud functions nodejs14 with 'latest' as include reference, got Invalid bucket name on exists()... still working for u?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.