hussain hussain - 1 month ago 17
Node.js Question

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

Answer

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