Last active
February 27, 2018 19:44
-
-
Save xirzec/6c015352ce89ed10144f066e518876d2 to your computer and use it in GitHub Desktop.
Count folder size
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"); | |
const util = require("util"); | |
const readFile = util.promisify(fs.readFile); | |
const readdir = util.promisify(fs.readdir); | |
const stat = util.promisify(fs.stat); | |
const ignoreList = ["node_modules", ".git"]; | |
const lineCountTypes = [".ts", ".tsx", ".js", ".html", ".css"]; | |
const NEW_LINE = 10; | |
async function main(root) { | |
console.log(root); | |
const files = await walk(root); | |
const types = await classify(files); | |
// sort in descending order | |
types.sort((a, b) => { | |
if (a.count > b.count) { | |
return -1; | |
} else if (a.count < b.count) { | |
return 1; | |
} else { | |
return 0; | |
} | |
}); | |
for(let item of types) { | |
console.log(item); | |
} | |
} | |
async function walk(dir) { | |
const remainingDirs = [dir]; | |
const files = []; | |
while(remainingDirs.length) { | |
const currentDir = remainingDirs.shift(); | |
const result = await readdir(currentDir); | |
for(const item of result) { | |
if (ignoreList.includes(item)) { | |
continue; | |
} | |
const itemPath = path.join(currentDir, item); | |
const itemStat = await stat(itemPath); | |
if(itemStat.isDirectory()) { | |
remainingDirs.push(itemPath); | |
} else { | |
files.push({ | |
name: item, | |
fullPath: itemPath, | |
sizeInBytes: itemStat.size | |
}); | |
} | |
} | |
} | |
return files; | |
} | |
async function classify(files) { | |
const types = new Map(); | |
for(const file of files) { | |
const ext = path.extname(file.name); | |
const typeInfo = types.get(ext) || { ext, count: 0, size: 0 }; | |
typeInfo.count++; | |
typeInfo.size += file.sizeInBytes; | |
if (lineCountTypes.includes(ext)) { | |
// get line count info | |
if (typeInfo.lines === undefined) { | |
typeInfo.lines = 0; | |
} | |
const contents = await readFile(file.fullPath); | |
let lineCount = 0; | |
let offset = 0; | |
do { | |
lineCount++; | |
offset = contents.indexOf(NEW_LINE, offset) + 1; | |
} while(offset > 0); | |
typeInfo.lines += lineCount; | |
} | |
types.set(ext, typeInfo); | |
} | |
return Array.from(types.values()); | |
} | |
main(process.argv[2]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment