Pulkit Bhardwaj
Pulkit Bhardwaj

Reputation: 58

Alternative to AWS' bucket.putObject() method in google-cloud/storage

I would like to mimic the following AWS call using the google-cloud/storage package

const params = {
                Body: data,
                Key: key,
                ContentType: type
            };
            return new Promise(function (resolve, reject) {
                bucket.putObject(params, function(error, data) {
                    if (error) {
                        console.log('ERROR: ', error);
                        reject(error);
                    }
                    resolve(data);                  
                });
            })

In the above call, if I pass some directory hierarchy in the Key param, the folder structure would be created and the file correctly placed.

For instance, if I pass the Key as root/test_folder/input_file.json Then the file would be placed as S3:///root/test_folder/input_file.json

I am unable to find a similar call in google-cloud/storage. If I use the

<bucket>.upload()

method, I can place the file under a directory, but I can ONLY upload files!

await storage.bucket(bucketName).upload(filename, {
        destination: 'abc/xyz',

If I use the

file.save()

method, I can put data into storage, but now I cannot put this under a specific directory!

await file.save(contents);

I need some way of putting content into a directory structure in google-storage and the directory structure may not exist.

Upvotes: 1

Views: 191

Answers (1)

Pulkit Bhardwaj
Pulkit Bhardwaj

Reputation: 58

Sorry I was wrong. This could simply be done with the file.save() method. We just need to specify the path along with the filename .

const {Storage} = require('@google-cloud/storage');

const storage = new Storage();
    const myBucket = storage.bucket('bucket');

    const file = myBucket.file('xxx/yyy/my-file', { generation: 0 });
    const contents = 'This is the contents of the file.';

    file.save(contents, function(err) {
      if (err) {
        file.deleteResumableCache();
      }
    });

The above would store the file under

bucket/xxx/yyy

Upvotes: 2

Related Questions