1
votes

I am trying to create a GCP Storage Bucket using the Node.js library. I've been using the steps here: https://cloud.google.com/storage/docs/creating-buckets#storage-create-bucket-nodejs

And code pasted below. The challenge is that my bucket keeps being created in the wrong project. My project is set in my gcloud cli, it's set in my node environment, and it's set in my script. Is there some way to set the project in the values you pass to the library's createBucket function?

/**
 * TODO(developer): Uncomment the following line before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const storageClass = 'Name of a storage class, e.g. coldline';
// const location = 'Name of a location, e.g. ASIA';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function createBucketWithStorageClassAndLocation() {
  // For default values see: https://cloud.google.com/storage/docs/locations and
  // https://cloud.google.com/storage/docs/storage-classes

  const [bucket] = await storage.createBucket(bucketName, {
    location,
    [storageClass]: true,
  });

  console.log(
    `${bucket.name} created with ${storageClass} class in ${location}.`
  );
}

createBucketWithStorageClassAndLocation();
1

1 Answers

5
votes

You can specify projectId when you initialize the Storage class:

const storage = new Storage({
  projectId: 'my-project-id',
  keyFilename: '/path/to/keyfile.json'
});

Source