Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
to free up disk space by deleting downloaded packages
#!/usr/bin/env node
let fs = require('fs');
let path = require('path');
let util = require('util');
let target = {
files: [
'workspace.xml',
],
dirs: [
'node_modules',
'elm-stuff',
'platforms',
'plugins',
'www',
'dist',
'.cache',
'.sourcemaps',
'deps',
'.erlang.mk',
],
};
function scanFile(filepath, filename) {
if (target.files.some(f => f === filename)) {
return fs.unlinkSync(filepath);
}
}
let count = {
file: 0,
dir: 0,
size: 0,
};
function formatSize(size) {
let units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
for (let i = 0; i < units.length; i++) {
if (size < 1024) {
return Math.round(size * 100) / 100 + units[i];
}
size /= 1024;
}
}
let lastReport = 0;
function report() {
let now = Date.now();
if (now - lastReport > 1000) {
lastReport = now;
process.stderr.write(`\r deleted: ${count.file} file | ${count.dir} dir | size: ${formatSize(count.size)} `);
}
}
function rmdir(dirpath, level = 0) {
let files = fs.readdirSync(dirpath);
files.forEach(filename => {
let filepath = path.join(dirpath, filename);
let stat = fs.lstatSync(filepath);
if (stat.isFile()) {
let size = stat.size;
report();
fs.unlinkSync(filepath);
count.file++;
count.size += size;
report();
return;
}
if (stat.isSymbolicLink()) {
let size = stat.size;
report();
fs.unlinkSync(filepath);
count.file++;
count.size += size;
report();
return;
}
if (stat.isDirectory()) {
rmdir(filepath, level + 1);
return;
}
console.log('not file nor dir:', filepath, stat);
});
report();
fs.rmdirSync(dirpath);
count.dir++;
report();
}
function scanDir(dirpath, dirname) {
if (target.dirs.some(d => d === dirname)) {
rmdir(dirpath);
return;
}
let files = fs.readdirSync(dirpath);
files.forEach(filename => {
let filepath = path.join(dirpath, filename);
let stat = fs.lstatSync(filepath);
if (stat.isFile()) {
return scanFile(filepath, filename);
}
if (stat.isDirectory()) {
return scanDir(filepath, filename);
}
});
}
{
let home = process.env.HOME;
let dirname = 'workspace';
let dirpath = path.join(home, dirname);
scanDir(dirpath, dirname);
process.stderr.write('\n');
console.log('total freed', formatSize(count.size));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment