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.
 
    