Skip to content

Instantly share code, notes, and snippets.

@Gergling
Last active October 10, 2018 13:48
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 Gergling/092ba290ca16de84b76a9110157b60ae to your computer and use it in GitHub Desktop.
Save Gergling/092ba290ca16de84b76a9110157b60ae to your computer and use it in GitHub Desktop.
Script to print the sizes of files in order of largest to smallest within their parent folders. Useful for investigating large folders for things which should be deleted or archived for space.
var fs = require("fs"); //Load the filesystem module
const { join } = require('path');
class FileNode {
constructor(path) {
const isDirectory = fs.lstatSync(path).isDirectory();
this.path = path;
if (isDirectory) {
// Get the children
this.children = fs.readdirSync(path).map(name =>
new FileNode(join(path, name)));
// Get the total based on the children.
this.setSize(this.children.reduce((total, child) =>
total + child.size, 0));
// Sort the children.
this.children.sort((a, b) =>
a.size === b.size
? 0
: (
a.size < b.size
? 1
: -1
)
);
} else {
this.setSize(fs.statSync(path)["size"]);
}
}
setSize(value) {
this.size = value;
this.base10LogFloor = Math.floor(Math.log(value) / Math.log(10)) + 1;
FileNode.sizeColumnWidth = Math.max(
FileNode.sizeColumnWidth || 0,
this.base10LogFloor
);
}
print() {
const paddingString = (this.size + '')
.padStart(FileNode.sizeColumnWidth, ' ');
console.log(paddingString, this.path);
if (this.children) {
this.children.forEach(child => child.print());
}
}
}
const root = new FileNode(process.argv[2]);
root.print();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment