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
callbackwhen are you usingunlinkSync? It should beunlinkif you want a callback.