Created
March 20, 2021 14:44
-
-
Save lawlesscreation/9ec5f2ecc4466576964f04c78e8131b6 to your computer and use it in GitHub Desktop.
Count classes in HTML files using Node
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
'use strict'; | |
const fs = require('fs'); | |
const path = require('path'); | |
console.log('🛠 Scanning HTML files...'); | |
const files = getAllFiles('./', ['.html']); | |
const classCount = countClasses(files); | |
console.log(`classes:`, classCount); | |
console.log(`found ${Object.keys(classCount).length} unique classes in ${files.length} files`); | |
function getAllFiles(initialPath, fileExtensions) { | |
var fullPaths = []; | |
var files = fs.readdirSync(initialPath); | |
files.forEach((file) => { | |
var joinedPath = path.join(initialPath, file); | |
if (fs.lstatSync(joinedPath).isDirectory()) { | |
fullPaths = fullPaths.concat(getAllFiles(joinedPath, fileExtensions)); | |
} else { | |
fileExtensions.forEach((fileExtension) => { | |
if (file.indexOf(fileExtension) >= 0 || fileExtension == null) { | |
fullPaths.push(joinedPath); | |
} | |
}); | |
} | |
}); | |
return fullPaths; | |
}; | |
function countClasses(files) { | |
const classCount = {}; | |
for (let index in files) { | |
if (files.hasOwnProperty(index)) { | |
const file = files[index]; | |
const htmlString = fs.readFileSync(file, 'utf8'); | |
const htmlClassRe = RegExp('class="[a-z\-\ ]*"','gi'); | |
const allClasses = []; | |
console.log(`finding classes in ${file}`); | |
const matches = htmlString.matchAll(htmlClassRe); | |
for (const match of matches) { | |
let newMatches = match[0].replace(/class="/g, '').replace(/"/g, '').trim().split(' '); | |
for (const newMatch of newMatches) { | |
allClasses.push(newMatch); | |
} | |
} | |
allClasses.forEach(className => { | |
classCount[className] = (classCount[className] || 0) + 1; | |
}); | |
} | |
}; | |
// Sort and return | |
return Object.entries(classCount).sort(([,a],[,b]) => b-a).reduce((r, [k, v]) => ({ ...r, [k]: v }), {});; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment