skip to Main Content

I am trying to migrate data in storage from documents/docId/file.name to users/userId/documents/docId/file.name. Is it possible to copy folders like documents/docId without needing to define "file.name"?

My code currently only works when I provide the exact file name. It looks like this:

const updateStorageData = async () => {
  return admin
    .storage()
    .bucket()
    .file('documents/1/Screenshot 2023-05-09 at 00.33.45.png')
    .copy(
      admin
        .storage()
        .bucket()
        .file('users/testID/documents/1/Screenshot 2023-05-09 at 00.33.45.png'),
    );
};

I would like to try to copy all files in the folder without needing to provide the exact file name. Is this possible?

2

Answers


  1. There no single API to copy all files in a folder, but you can list the files in a folder and then copy them one-by-one in a loop.

    Login or Signup to reply.
  2. You need to use the getFiles() and move() methods along the following lines:

    const getFilesResponse = await admin
        .storage()
        .bucket()
        .getFiles();
    const arrayOfFiles = getFilesResponse[0];
    
    const promises = [];
    arrayOfFiles.forEach(file => {
        // Check if the file needs to be moved based on its path (or metadata)
        if (fileToBeMoved) {
            promises.push(file.move('....png'))
        }
    });
    
    await Promise.all(promises)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search