Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Question - How do I delete the (temp) files on the server? #17

Closed
viditmaniyar opened this issue Aug 11, 2016 · 2 comments
Closed

Question - How do I delete the (temp) files on the server? #17

viditmaniyar opened this issue Aug 11, 2016 · 2 comments
Labels

Comments

@viditmaniyar
Copy link

Hello!
I see the followingin the Readme file -

// don't forget to delete all req.files when done

How do I achieve/implement this?

Any help is appreciated. Thanks!

@dougwilson
Copy link
Contributor

Hi @IamRudra, you should do this in two parts:

  1. Always ensure that your os.tempDir() (or whatever you pass as the uploadDir option) is periodically reaped by your OS (for example, using a cron job on Linux).
  2. In your Node.js code, after processing, iterate through the req.files and use fs.unlink to delete all the files. The note is there to call out that you cannot simply only call fs.unlink on the files you handled; you have to delete everything in the req.files object.

@peterdemin
Copy link

Just in case someone is looking for a code snippet to do this, here's the GPT-3.5 code example:

const express = require('express');
const multipart = require('connect-multiparty');
const fs = require('fs');

const app = express();

// Middleware for file uploads
app.use(multipart());

// Route for file upload
app.post('/upload', (req, res) => {
  // Access uploaded files through req.files
  const uploadedFiles = req.files;

  // Iterate through uploaded files and delete them
  for (const fileKey in uploadedFiles) {
    const filePath = uploadedFiles[fileKey].path;

    // Delete the file using fs.unlink
    fs.unlink(filePath, (err) => {
      if (err) {
        console.error(`Error deleting file ${filePath}:`, err);
      } else {
        console.log(`Successfully deleted file ${filePath}`);
      }
    });
  }

  // Send response
  res.send('Files deleted');
});

// Start the server
app.listen(3000, () => {
  console.log('Server listening on port 3000');
});

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

3 participants