Move/rename folder in Google Cloud Storage using nodejs gcloud api
Asked Answered
B

2

10

I am trying to rename or move a folder in google cloud storage using the gcloud api.

A similar question explains how to delete a folder: Delete folder in Google Cloud Storage using nodejs gcloud api

But how can one rename a folder? or move to another path?

Bloodcurdling answered 10/12, 2016 at 11:38 Comment(1)
You can also use cloud.google.com/storage/transfer to do one-time or recurring transfers from one bucket to another.Whipsaw
A
12

You can try something like this:

'use strict'

var async = require('async')
var storage = require('@google-cloud/storage')()
var bucket = storage.bucket('stephen-has-a-new-bucket')

bucket.renameFolder = function(source, dest, callback) {
  bucket.getFiles({ prefix: source }, function(err, files) {
    if (err) return callback(err)

    async.eachLimit(files, 5, function(file, next) {
      file.move(file.name.replace(source, dest), next)
    }, callback)
  })
}

bucket.renameFolder('photos/cats', 'photos/dogs', console.log)
Alcahest answered 13/12, 2016 at 2:58 Comment(1)
Thanks, but once the files are moved, they are no long public. Is there a way to maintain the public attribute?Flagellate
W
4

There are no folders. There is simply a collection of objects that all happen to have the same key prefix, for example photos/animals/cat.png and photos/animals/dog.png both have a common prefix photos/animals/ and that's what makes them appear to be in the same folder.

You will need to copy (or move) each of the objects to its new key, for example move photos/animals/cat.png to photos/pets/cat.png and move photos/animals/dog.png to photos/pets/dog.png.

That said, Google Cloud provides a way to do this from the command line using gsutil mv.

Whipsaw answered 11/12, 2016 at 20:8 Comment(2)
How can You move Bucket/A/B/2018-09-23 to Bucket/A/2018-09-23 ? mv doesn't support itPhrygian
@Phrygian the mv command claims to be able to rename subfolders.Whipsaw

© 2022 - 2024 — McMap. All rights reserved.