Created
July 15, 2022 15:03
-
-
Save alexanderson1993/6032166bb11a01aa8b3ed61f8c6e25ba to your computer and use it in GitHub Desktop.
A tool for recursively counting the number of lines in each file in a directory
This file contains 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
import fs from 'fs/promises'; | |
console.time('Get file sizes'); | |
const items = await fs.readdir('.'); | |
const ignore = [ | |
'_templates', | |
'.git', | |
'.github', | |
'.next', | |
'.storybook', | |
'.vscode', | |
'node_modules', | |
'scripts', | |
'jobs', | |
'prisma', | |
]; | |
const ignoreFiles = ['.DS_Store']; | |
const filtered = ( | |
await Promise.all( | |
items | |
.filter((item) => !ignore.includes(item)) | |
.map(async (item) => { | |
if ((await fs.lstat(`./${item}`)).isDirectory()) return `./${item}`; | |
return null; | |
}) | |
) | |
).filter(Boolean); | |
async function recursiveCheck(files: string[]) { | |
const results: { [key: string]: number } = {}; | |
for (const file of files) { | |
const items = await fs.readdir(file); | |
const dirs: string[] = []; | |
for (const item of items) { | |
if ( | |
ignoreFiles.includes(item) || | |
item.endsWith('.png') || | |
item.endsWith('.ico') || | |
item.endsWith('.otf') | |
) | |
continue; | |
if ((await fs.lstat(`${file}/${item}`)).isDirectory()) { | |
dirs.push(`${file}/${item}`); | |
} else { | |
const data = await fs.readFile(`${file}/${item}`, 'utf-8'); | |
const lines = data.split('\n').length; | |
results[`${file}/${item}`] = lines; | |
} | |
const output = await recursiveCheck(dirs); | |
Object.assign(results, output); | |
} | |
} | |
return results; | |
} | |
const counts = await recursiveCheck(filtered); | |
Object.entries(counts) | |
.sort(([__, a], [_, b]) => { | |
if (a < b) return 1; | |
if (b < a) return -1; | |
return 0; | |
}) | |
.forEach(([path, count]) => console.log(String(count).padStart(3, ''), path)); | |
console.timeEnd('Get file sizes'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment