macos – How can I delete node_modules folders in projects that I have not recently touched?
I should have had some patience.. instead of posting the question here first. I think I have a solution.
~/bin/clean_old_projects.js
const { readdirSync, statSync, rmSync } = require('node:fs')
const {execSync} = require('node:child_process')
const getDirectories = source => {
try {
return readdirSync(source, { withFileTypes: true })
.filter(dirent => dirent.isDirectory())
.map(dirent => `${source}/${dirent.name}`)
}
catch (e) { return [] }
}
targets = [process.env.HOME]
nodeProjects = []
for (let target of targets) {
if (/node_modules$/.test(target)) {
nodeProjects.push(target.replace('/node_modules', ''))
} else {
targets.push(...getDirectories(target))
}
}
const sh = fh => `find "${fh}" -name node_modules -prune -o -type f -print0 | xargs -0 stat -f "%m %N" | sort -rn | head -1 | cut -f2- -d" "`
const fourWeeks = 2419200
const now = new Date()
for (let target of nodeProjects) {
const fh = execSync(sh(target)).toString().trim()
if(now - statSync(fh.length? fh: target).mtime > fourWeeks)
rmSync(target + '/node_modules', { recursive: true, force: true })
}
then crontab -e
and save:
0 3 14,28 * * /usr/local/bin/node /Users/MY_HOME_DIRECTORY/bin/clean_old_projects.js
Categories