Created
July 15, 2020 10:10
-
-
Save andrewgreenh/189bda48647de085e1663cbef3e75dcc to your computer and use it in GitHub Desktop.
This file contains hidden or 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
const fs = require('fs'); | |
const path = require('path'); | |
async function main() { | |
const pathsFile = await fs.promises.readFile(path.join(__dirname, 'paths')); | |
const paths = pathsFile | |
.toString('utf8') | |
.split(/\r\n?/) | |
.map(line => line.trim()) | |
.filter(line => line !== ''); | |
for (const pathItem of paths) { | |
for await (const fileOrDir of getChildPathsRecursively(pathItem)) { | |
const stat = await fs.promises.stat(fileOrDir); | |
const ageInDays = (Date.now() - stat.mtimeMs) / 1000 / 60 / 60 / 24; | |
if (ageInDays > 7 && !stat.isDirectory()) { | |
await fs.promises.unlink(fileOrDir); | |
} | |
if (stat.isDirectory() && (await fs.promises.readdir(fileOrDir)).length === 0) { | |
await fs.promises.rmdir(fileOrDir); | |
} | |
} | |
} | |
} | |
async function* getChildPathsRecursively(currentPath, level = 0) { | |
const childDirents = await fs.promises.readdir(currentPath, { | |
withFileTypes: true, | |
encoding: 'utf8' | |
}); | |
const files = childDirents.filter(p => p.isFile()); | |
const subDirs = childDirents.filter(p => p.isDirectory()); | |
for (const subDir of subDirs) { | |
yield* getChildPathsRecursively(path.join(currentPath, subDir.name), level + 1); | |
} | |
for (const file of files) { | |
const filePath = path.join(currentPath, file.name); | |
yield filePath; | |
} | |
for (const subDir of subDirs) { | |
yield path.join(currentPath, subDir.name); | |
} | |
} | |
main().catch(err => console.error(err)); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment