Last active
February 13, 2023 03:56
-
-
Save tangxinfa/ceaf31d8c14231617cf05dc7a6b2555c to your computer and use it in GitHub Desktop.
how to delete file after download in node.js
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'), | |
express = require('express'), | |
app = express(); | |
function deleteFile (file) { | |
fs.unlink(file, function (err) { | |
if (err) { | |
console.error(err.toString()); | |
} else { | |
console.warn(file + ' deleted'); | |
} | |
}); | |
} | |
app.get('/deleteAfterDownload', function (req, res) { | |
var filename = "file.dat"; | |
var stream = fs.createReadStream(filename); | |
stream.pipe(res).once("close", function () { | |
stream.destroy(); // makesure stream closed, not close if download aborted. | |
deleteFile(filename); | |
}); | |
}); | |
app.listen(80); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@sudheer5
In your code snippet, it just created a stream, it need to do something to close
the stream, such as:
The
Stream.pipe
api will close the input stream after finish reading, or you canclose the input stream manually.
You can try to add logging statements in "close" event handler, to see if it
really closed.