nodejs multer diskstorage to delete file after saving to disk nodejs multer diskstorage to delete file after saving to disk express express

nodejs multer diskstorage to delete file after saving to disk


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!")})


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})


You may also consider using MemoryStorage for this purpose, with this storage the file is never stored in the disk but in memory and is deleted from the memory automatically after execution comes out of controller block, i.e., after you serve the response in most of the cases.

When you will use this storage option, you won't get the fields file.destination, file.path and file.filename, instead you will get a field file.buffer which as name suggests is a buffer, you can convert this buffer to desired format to do operations on and then upload using a stream object.

Most of the popular libraries support streams so you should be able to use stream to upload your file directly, code for converting buffer to stream:

const Readable = require('stream').Readable;var stream = new Readable();stream._read = () => { }stream.push(file.buffer);stream.push(null);// now you can pass this stream object to your upload function

This approach would be more efficient as files will be stored in memory which will result in faster access, but it does have a con as mentioned in multer documentation:

WARNING: Uploading very large files, or relatively small files inlarge numbers very quickly, can cause your application to run out ofmemory when memory storage is used.