multi-countwords
Version:
it is a npx cli project which can count words in any file
60 lines (44 loc) • 1.42 kB
JavaScript
import fs, { readFile } from "fs/promises"
if(process.argv.length === 2) {
console.log('Pass File path', '\r\n\r\n', 'example = count {filepath} {wordstosearch}', '\r\n\r\n', 'you can search multiple words by seprating them with space');
process.exit()
} else if (process.argv.length === 3) {
console.log('Pass at least one word');
process.exit()
}
const filePath = process.argv[2]
const passedWords = process.argv.slice(3, process.argv.length)
// console.log(passedWords);
const fileContent = await readFile(filePath, "utf-8")
const wordsArray = fileContent.split(/[\W]/).filter((word) => word)
const wordsCount = {}
wordsArray.forEach((word) => {
if (wordsCount[word]) {
wordsCount[word] += 1
} else {
wordsCount[word] = 1
}
})
const keys = Object.keys(wordsCount)
function keepSameWords(wordobj, words) {
const toFind = keys.filter((key) => words.includes(key))
keys.forEach((key) => {
if (toFind.includes(key)) {
} else {
delete wordobj[key]
}
})
if (JSON.stringify(wordobj) === "{}") {
console.log(
"\x1b[94m%s\x1b[0m \x1b[1m\x1b[91m%s\x1b[0m",
"words not found:",
`${words.join(", ")}`
)
// console.log(wordsCount)
} else {
console.log(wordobj)
}
}
const wordsCountClone = { ...wordsCount }
keepSameWords(wordsCountClone, passedWords)