How to move files with firebase storage?

Is there a way to move files with firebase.storage()?

Example: user1/public/image.jpg to user1/private/image.jpg


Since Firebase Storage is backed by Google Cloud Storage, you can use GCS's rewrite API (docs) or gsutil mv (docs).

Also, an example of move (docs) in GCloud Node follows:

var bucket = gcs.bucket('my-bucket');
var file = bucket.file('my-image.png');
var newLocation = 'gs://another-bucket/my-image-new.png';
file.move(newLocation, function(err, destinationFile, apiResponse) {
  // `my-bucket` no longer contains:
  // - "my-image.png"
  //
  // `another-bucket` now contains:
  // - "my-image-new.png"

  // `destinationFile` is an instance of a File object that refers to your
  // new file.
});

There is no such way to move to other location, rather you can download and then put it to other reference and deleting the previous location.


I wrote a JavaScript function that accomplishes this using only the firebase storage API.

Happy Coding!

/**
 * Moves a file in firebase storage from its current location to the destination
 * returns the status object for the moved file.
 * @param {String} currentPath The path to the existing file from storage root
 * @param {String} destinationPath The desired pathe for the existing file after storage
 */
function moveFirebaseFile(currentPath, destinationPath) {
    let oldRef = storage.ref().child(currentPath)

    oldRef.getDownloadURL().then(url => {
        fetch(url).then(htmlReturn => {
            let fileArray = new Uint8Array()
            const reader = htmlReturn.body.getReader()

            //get the reader that reads the readable stream of data
            reader
                .read()
                .then(function appendStreamChunk({ done, value }) {
                    //If the reader doesn't return "done = true" append the chunk that was returned to us
                    // rinse and repeat until it is done.
                    if (value) {
                        fileArray = mergeTypedArrays(fileArray, value)
                    }
                    if (done) {
                        console.log(fileArray)
                        return fileArray
                    } else {
                        // "Readout not complete, reading next chunk"
                        return reader.read().then(appendStreamChunk)
                    }
                })
                .then(file => {
                    //Write the file to the new storage place
                    let status = storage
                        .ref()
                        .child(destinationPath)
                        .put(file)
                    //Remove the old reference
                    oldRef.delete()

                    return status
                })
        })
    })
}