I'm trying to delete some files in a folder using the module fs. I need to delete a file only if it is older (modified time) that 1 minute. But I get a strange error.
var fs = require("fs");
var files = fs.readdirSync("./folder");
for (var i in files) {
fs.stat("./folder/" + files[i], function (err, stats) {
var currentTimestamp = Math.round(new Date().getTime() / 1000);
var fileTimestamp = Math.round((new Date(stats.mtime).getTime() / 1000));
if ((currentTimestamp - fileTimestamp) > 60 * 1) {
//Elimino il file di cache
fs.unlinkSync("./folder/" + files[i], function (err) {
if (err) {
console.log(err);
} else {
console.log("File deleted");
}
});
}
});
}
Unfortunately I get this error
fs.js:765
return binding.unlink(pathModule._makeLong(path));
^
Error: ENOENT, no such file or directory
Why does this happen? How can I solve ?? Thanks
EDIT
I make a log before the fs.unlinkSync("./folder/" + files[i], function (err)
and I see that is called 2 times with the same file... but there is only one file in the folder.... with that name
Below is the problem:-
You are doing fs.stat
an async call in for loop
. And for
is a sync
block. There are chances that it will be called after the end of your for
loop. In the end, it will call all callbacks with last value of i
.
Since value of i
is same it will search for the same file more than once and it will end up throwing an error.
There are two solutions to your problem.
1) Use fs.statSync
& fs.unlinkSync
so it will be sync call. The value of i
won't increment until the whole loop executes, but it's not the good way of doing it.
2) Use Array.forEach
because it is an async
process, so it will call the function on each file. I will prefer this method.
I've modified your problem and got it working with Array.forEach
.
var fs = require("fs");
var files = fs.readdirSync("./Folder");
var deleteFile = function (fileName) {
fs.stat("./Folder/" + fileName, function (err, stats) {
var currentTimestamp = Math.round(new Date().getTime() / 1000);
var fileTimestamp = Math.round((new Date(stats.mtime).getTime() / 1000));
if ((currentTimestamp - fileTimestamp) > 60 * 1) {
//Elimino il file di cache
console.log('deleting ',fileName)
fs.unlink("./Folder/" + fileName, function (err) {
if (err) {
console.log(err);
} else {
console.log("File deleted");
}
});
}
});
}
files.forEach(deleteFile);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.