Skip to content

Instantly share code, notes, and snippets.

@andrewgreenh
Created July 15, 2020 10:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andrewgreenh/189bda48647de085e1663cbef3e75dcc to your computer and use it in GitHub Desktop.
Save andrewgreenh/189bda48647de085e1663cbef3e75dcc to your computer and use it in GitHub Desktop.
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