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); |
Hi, I used the above code to delete file, but file is not deleted and I'm not even getting error in fs.unlink, please help me
Here is the code:
var stream = fs.createReadStream(targetPath, { emitClose: true });
stream.on('end', function () {
console.log('data read successfully');
stream.close();
});
stream.on('error', function () {
console.log('error in reading the data');
});
stream.on('data', function () {
console.log("receiving the data");
})
stream.on("close", function () {
stream.destroy((err) => {
if (err) {
console.log("error in destroying the stream " + err);
}
});
fs.unlink(targetPath, function (err) {
if (err) {
console.log(`Error in deleting the file: ${err}.`);
} else {
console.log(`Successfully deleted the file.`);
}
});
});
In your code snippet, it just created a stream, it need to do something to close
the stream, such as:
stream.pipe(process.stdout);
The Stream.pipe
api will close the input stream after finish reading, or you can
close the input stream manually.
You can try to add logging statements in "close" event handler, to see if it
really closed.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
@thekoushik - That worked for me too, thanks!