B
B
Bogdan2019-03-18 16:51:41
Node.js
Bogdan, 2019-03-18 16:51:41

Delete undownloaded file?

Hello. Tell me please. How can I delete an undownloaded file: user cancellation, connection failure? For loading I use Multer. In the req.on('close', ..) event, I catch the connection cancellation, but the file is not deleted (although it writes about deletion in the logs), it cannot be deleted manually either, it seems like the stream is holding it. Thank you.

const pathApp = 'app';
const pathUploads = path.join(__dirname, '..', process.env.APP_PATH_UPLOADS, pathApp);
const filenameApp = 'еее.apk';
const filenameAppTmp = `tmp_${filenameApp}`;
const fullPathApp = path.join(pathUploads, filenameApp);
const fullPathAppTmp = path.join(pathUploads, filenameAppTmp);

const fileFilter = async (req, file, next) => {
  if (!fs.existsSync(pathUploads)) fs.mkdirSync(pathUploads);

  return next(null, true);
};

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, pathUploads);
  },
  filename(req, file, cb) {
    cb(null, filenameAppTmp);
  }
});

const upload = multer({
  fileFilter,
  storage
});

routes.post('/upload', (req, res, next) => {
  req.on('close', async () => {
    fs.unlink(fullPathAppTmp, err => {
      if (err) return console.log(err);
      console.log('path/file.txt was deleted');
    });
  });

  upload.single('file')(req, res, next);

  req.on('end', () => {
    fs.rename(fullPathAppTmp, fullPathApp, err => {
      if (err) throw err;
    });
    res.status(204).send();
  });
});

Answer the question

In order to leave comments, you need to log in

1 answer(s)
I
Ivan Shumov, 2019-03-18
@inoise

You don't have to delete it right away, but over time.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question