Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs multer diskstorage to delete file after saving to disk

I am using multer diskstorage to save a file to disk. I first save it to the disk and do some operations with the file and then i upload it to remote bucket using another function and lib. Once the upload is finished, i would like to delete it from the disk.

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, '/tmp/my-uploads')
  },
  filename: function (req, file, cb) {
    cb(null, file.fieldname + '-' + Date.now())
  }
})

var upload = multer({ storage: storage }).single('file')

and here is how i use it:

app.post('/api/photo', function (req, res) {
    upload(req, res, function (err) {
        uploadToRemoteBucket(req.file.path)
        .then(data => {
            // delete from disk first

            res.end("UPLOAD COMPLETED!");
        })
    })
});

how can i use the diskStorage remove function to remove the files in the temp folder? https://github.com/expressjs/multer/blob/master/storage/disk.js#L54

update:

I have decided to make it modular and put it in another file:

const fileUpload = function(req, res, cb) {
    upload(req, res, function (err) {
        uploadToRemoteBucket(req.file.path)
        .then(data => {
            // delete from disk first

            res.end("UPLOAD COMPLETED!");
        })
    })
}

module.exports = { fileUpload };
like image 968
jacky Avatar asked Mar 04 '18 19:03

jacky


2 Answers

Multer isn't needed. Just use this code.

const fs = require('fs')

const path = './file.txt'

fs.unlink(path, (err) => {
  if (err) {
    console.error(err)
    return
  }

  //file removed
})
like image 90
sqrepants Avatar answered Oct 27 '22 01:10

sqrepants


You don't need to use multer to delete the file and besides _removeFile is a private function that you should not use.

You'd delete the file as you normally would via fs.unlink. So wherever you have access to req.file, you can do the following:

const fs = require('fs')
const { promisify } = require('util')

const unlinkAsync = promisify(fs.unlink)

// ...

const storage = multer.diskStorage({
    destination(req, file, cb) {
      cb(null, '/tmp/my-uploads')
    },
    filename(req, file, cb) {
      cb(null, `${file.fieldname}-${Date.now()}`)
    }
  })

const upload = multer({ storage: storage }).single('file')

app.post('/api/photo', upload, async (req, res) =>{
    // You aren't doing anything with data so no need for the return value
    await uploadToRemoteBucket(req.file.path)

    // Delete the file like normal
    await unlinkAsync(req.file.path)

    res.end("UPLOAD COMPLETED!")
})
like image 40
Francisco Mateo Avatar answered Oct 27 '22 00:10

Francisco Mateo