Skip to content

Instantly share code, notes, and snippets.

@bennycode
Created April 1, 2020 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 bennycode/42ca0a5c98f037ca6dc6e728061b85e4 to your computer and use it in GitHub Desktop.
Save bennycode/42ca0a5c98f037ca6dc6e728061b85e4 to your computer and use it in GitHub Desktop.
Traverse directories and show lines of code
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