I have directory with files.
I would like to delete (zip) files which were created before 7days ago.
I would like to run this script every day.
I can get all files in dir using:
fs.readdirSync('/data/mongodump/').forEach(file => {
console.log(file);
});
But I dont know how to compare (get) dates, then I can call unlink
.
Can anyone help me?
You can you FS.statsSync()
native API where ctime
is the last changed time, but you can also use birthtime
for creation date.
Documentation:https://nodejs.org/api/fs.html#fs_fs_stat_path_options_callback
fs.readdirSync('/data/mongodump/').forEach(file => {
const isOlder = fs.statSync(`/data/mongodump/${file}`).ctime < Date.now() - 604800000 // 604800000 = 7 * 24 * 60 * 60 * 1000
if (isOlder) {
fs.unlinkSync(`/data/mongodump/${file}`)
}
})
Bests,
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.