2

I have two async functions:

  1. One for creating objects in PostgreSQL and upload files with named in this object.
  2. Another one for deleting this entity and deleting files from folder.

I don't know how to extract filenames from PostgreSQL entity and delete certain files in my 'static' folder

Entity in PostgreSQL looks like:

Car:
  {
   'name': 'Nissan 350Z',
   'description': 'new',
   'image': '123wejdsefberfkj.jpg',
   'video': '23rusdjf8ioysdfs.mp4'
  }

Create function:

Here I get files from form-data, create unique name for files and save it in PostgreSQL, then I save files in "static" folder.

 let videoName = uuid.v4() + '.mp4';
 let imageName = uuid.v4() + '.jpg';
 let {name,description} = req.body;
 const {video, image} = req.files; 
 const car = await Car.create( {name, description, video: videoName,image: imageName})
                .then(video.mv(path.resolve(__dirname,'..', 'static', videoName)))
                .then(image.mv(path.resolve(__dirname,'..', 'static', imgName)))

Delete function:

Here I need to extract file-names from database and delete them from folder

a bit pseudocode:

async delete(req, res) {
        try {
            const {id} = req.params;
            await Car.findOne({where:{id}})
                .then( async data => {
                    if(data) {
                        await let videoName = Car.@extract_video_name@ ({where: {id}})
                              .then(mv(path.delete(__dirname,'..','static',videoName)))
                        await Car.destroy({where:{id}}).then(() => {
                            return res.json("Car deleted");
                        })
                    } else {
                        return res.json("This Car doesn't exist in database");
                    }
                })
            
        } catch (e) {
            console.error(e)
        }
    }

1 Answers1

5

You can use fs, require it using const fs = require('fs');

You have no npm package to install, it's included in node.js.

This is the code that allows you to save your files into a directory by creating the folder if it doesn't exist and upload the file into it

  let path = String(`./directoryName/${fileName}`);
    fs.mkdirSync('./directoryName', { recursive: true });
    fs.writeFileSync(path, data);

And you can delete the file using

  fs.unlink(path, (err) => {
  if (err) throw err //handle your error the way you want to;
  console.log('path/file.txt was deleted');//or else the file will be deleted
    });
  );

Refernce : https://nodejs.org/api/fs.html

nermineslimane
  • 541
  • 4
  • 21