Warm tip: This article is reproduced from serverfault.com, please click

Remove file using MulterGoogleStorage and NestJS

发布于 2020-11-28 08:41:28

How to remove file from Google storage bucket using MulterGoogleStorage and NestJS? I can't find any example or docs. I have next storage for upload files:

const storage = new MulterGoogleStorage({
  projectId: 'myprojectId',
  keyFilename: path.join(__dirname, '../../../mykeyfile.json'),
  bucket: 'mybucketname',
  filename: (req: Request, file, cb) => {
    let dir = '';
    const filePath = file.originalname.split('/');        
    if(filePath.length > 1) {
        dir = `${filePath[0]}/`;
    }
    const fileExt = file.originalname.split('.').pop();
    cb(null, `${dir}${Date.now()}.${fileExt}`);
  }
});
Questioner
V.Tur
Viewed
11
Stefan Neacsu 2020-11-30 16:14:27

You can create something like this, which would iterate over an array containing all the objects, and would delete.

This uses the delete function on the Google Cloud Storage documentation.

const storage = new Storage({keyFilename: 'google-credentials.json'});
const imagesToDelete = ['fileName1', 'fileName2', 'fileName3'];
    
    imagesToDelete.map(async (image) => {
      await storage
        .bucket('yourbucketName')
        .file(image)
        .delete();
    });