Harikrishnan
Harikrishnan

Reputation: 3822

Deleting file in node.js not working

I am using Node.js with Express. I am trying to delete a file after sending it to client with express js.

function deleteFile (file) { 
    fs.unlink(file, function (err) {
        if (err) {
            logger.error(err);
        }
    });
}

app.get("/deleteFileAfterDownload", function (req, res){
    var fileName = "a.pdf"
    var stream = fs.createReadStream(fileName);
    var streamClosed = false;
    req.on('end',function(){ 
        if (!streamClosed){  
            stream.emit('close');
            // I tried stream.destroy() but that is also not working
        }
    });
    stream.on('close', function () {
        streamClosed = true; 
        deleteFile(fileName);
    });
    req.on('data', function(){});  
    stream.pipe(res);
});

But the file is not getting deleted. it seems the process is still using file because just after I end the process, the file is getting deleted.

Can anybody tell me why? If I am doing it wrong, please tell me a good way.

Upvotes: 1

Views: 1967

Answers (1)

tangxinfa
tangxinfa

Reputation: 1520

Please add a log in deleteFile, makesure it is called.

Try simplify it:

var fileName = "a.pdf"
var stream = fs.createReadStream(fileName);
stream.pipe(res);
res.once("finish", function () {
    deleteFile(fileName);
});

The previous example only delete file if download finished, if you want delete file unconditionly, try the following:

var fileName = "a.pdf";
var stream = fs.createReadStream(fileName);
stream.pipe(res).once("close", function () {
    stream.close();
    deleteFile(fileName);
});

stream.close() is important here, because stream not close if pipe aborted.

Upvotes: 2

Related Questions