How can I create empty folder inside GCP Cloud Storage bucket using NodeJS?

203 Views Asked by At

I have a bucket my-bucket-101 inside it I have categories folder in which want to create 200 folders representing categories, initially those would be empty.

import { Storage } from '@google-cloud/storage';

const bucketName = 'my-bucket-101';

export async function addFolder(folderName) {
  const storage = new Storage({ keyFilename: './key.json' });
  const bucket = storage.bucket(bucketName);
  const resp = bucket.upload('', {destination: `categories/${folderName}`, (err, file) => {
    if (err) {
      throw new Error(`${err}`);
    }
    console.log(file);
  });

  console.log(`Resp from bucket.upload: ${resp}`);
  console.log(`Folder created inside coaches: ${folderName}`);
}

When I upload it says - 'ENOENT: no such file or directory, open'

I know this may be because of empty string I'm passing in upload method, but I don't know other method to create empty folder in GCS. Any help would be much appreciated.

1

There are 1 best solutions below

2
Ninja-aman On

I solved it by uploading a test file

import { Storage } from '@google-cloud/storage';

const bucketName = 'my-bucket-101';

export function addFolder(folderName: string) {
    const storage = new Storage({ keyFilename: './key.json' });
    const bucket = storage.bucket(bucketName);
    bucket.upload('test.json', { destination: `categories/${folderName}/` }, (err, file) => {
        if (err) {
            throw new Error(err.message);
        }
        console.log(file);
    });
    console.log(`Folder "${folderName}" created in "categories/".`);
}