Created
April 1, 2020 13:48
-
-
Save bennycode/42ca0a5c98f037ca6dc6e728061b85e4 to your computer and use it in GitHub Desktop.
Traverse directories and show lines of code
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
const fs = require('fs'); | |
const path = require('path'); | |
function walkDir(dir, callback) { | |
fs.readdirSync(dir).forEach(file => { | |
const dirPath = path.join(dir, file); | |
const isDirectory = fs.statSync(dirPath).isDirectory(); | |
isDirectory ? | |
walkDir(dirPath, callback) : callback(path.join(dir, file)); | |
}); | |
} | |
function countLines(filePath) { | |
return new Promise((resolve, reject) => { | |
let count = 0; | |
fs.createReadStream(filePath) | |
.on('error', reject) | |
.on('data', chunk => { | |
for (let i = 0; i < chunk.length; ++i) if (chunk[i] === 10) count++; | |
}) | |
.on('end', () => resolve(count)); | |
}); | |
} | |
const dir = process.cwd(); | |
console.log(`Walking through directory "${dir}".`); | |
walkDir(dir, async (filePath) => { | |
if (filePath.endsWith('.js')) { | |
const loc = await countLines(filePath); | |
console.log(`- [ ] ${filePath.substr(dir.length + 1)} (${loc} lines)`); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment