Skip to content

Instantly share code, notes, and snippets.

@jafar-jabr
Last active March 5, 2022 02:11
Show Gist options
  • Save jafar-jabr/a33683c8c68a52c3a3ec182e16b9356c to your computer and use it in GitHub Desktop.
Save jafar-jabr/a33683c8c68a52c3a3ec182e16b9356c to your computer and use it in GitHub Desktop.
Count files and lines
const fs = require("fs");
const readline = require('readline');
/**
*
* @param folderPath
* @param extensions
* @returns {boolean}
*/
const countFilesAndLines = async (folderPath, extensions) => {
let files = 0;
let lines = 0;
const doRead = (_file) => {
let lineCount = 0;
return new Promise((resolve) => {
const inf = readline.createInterface({
input: fs.createReadStream(_file),
crlfDelay: Infinity
});
inf.on('line', (line) => {
if(line.trim()?.length) {
lineCount += 1;
}
});
inf.on('close', () => resolve(lineCount));
});
}
const counter = async(_path) => {
try {
await Promise.all(fs
.readdirSync(_path, { withFileTypes: true })
.map(async (subDir) => {
const extension = subDir.name.split('.').pop();
if(subDir.isFile() && extensions.indexOf(extension) > -1){
const t = await doRead(`${_path}/${subDir.name}`);
lines += t;
files += 1;
} else if(subDir.isDirectory()){
const subPath = `${_path}/${subDir.name}`;
await counter(subPath);
}
}));
} catch (err) {
console.warn(err);
}
}
await counter(folderPath);
return {files, lines};
};
/* countFilesAndLines('/root/pathto/Work/some/directory', ['ts', 'tsx', 'txt', 'js', 'jsx']).then((result) => {
console.warn(`result ${JSON.stringify(result)}`);
}); */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment