hussain
hussain

Reputation: 7083

How to remove file from directory once upload is done?

I want to remove files from app/ directory once upload response sent back to client. How can i achieve that task using nodejs ?

server.js

var fs = require('fs');
var multer  = require('multer');
var upload = multer({dest:'app/'}).single('file');
export function create(req, res) {

  upload(req, res, function (err) {
    if (err) {
     console.log("error occurred");
    }else{
        console.log(req.file.path);
        var fileContent = fs.readFileSync(req.file.path,'utf8');
        res.json(fileContent);
    }
  });
}

Upvotes: 0

Views: 75

Answers (1)

user5734311
user5734311

Reputation:

Just do this:

 var fileContent = fs.readFileSync(req.file.path,'utf8');
 fs.unlink(req.file.path);
 res.json(fileContent);

I'll recommend to not use Sync functions though:

fs.readFile(req.file.path,'utf8', function(err, data) {
    if (err) throw err;
    res.json(data);
    fs.unlink(req.file.path);
});

Upvotes: 2

Related Questions