varun-word-counter-cli
Version:
A CLI tool to count words in a text file
68 lines (55 loc) ⢠1.78 kB
JavaScript
import fs from "fs/promises";
const filePath = process.argv[2];
const searchWord = process.argv[3];
// š Show Help
if (!filePath || filePath === "--help" || filePath === "-h") {
console.log(`
š§® Word Counter CLI
Usage:
wordcount <file-path> [word-to-search]
Examples:
wordcount ./sample.txt
wordcount ./sample.txt success
Description:
Counts all words in a given text file.
Optionally, count how many times a specific word appears.
`);
process.exit(0);
}
if (!filePath) {
console.error("ā Error: Please provide a file path as the first argument.");
process.exit(1);
}
try {
const fileContent = await fs.readFile(filePath, "utf-8");
const wordsArray = fileContent
.split(/[\W_]+/) // split by non-word characters, including underscore
.filter((w) => w); // remove empty strings
const wordCount = {};
wordsArray.forEach((word) => {
const lowerWord = word.toLowerCase();
wordCount[lowerWord] = (wordCount[lowerWord] || 0) + 1;
});
if (searchWord) {
const lowerSearchWord = searchWord.toLowerCase();
const count = wordCount[lowerSearchWord] || 0;
console.log(`š '${searchWord}' appears ${count} time(s).`);
} else {
console.log("š Word Frequency Count:");
Object.entries(wordCount).forEach(([word, count]) => {
console.log(`- ${word}: ${count}`);
});
}
} catch (err) {
if (err.code === "ENOENT") {
console.error(`ā Error: File '${filePath}' not found.`);
} else if (err.code === "EACCES") {
console.error(
`ā Error: Permission denied to read the file '${filePath}'.`
);
} else {
console.error("ā Unexpected Error:", err.message);
}
process.exit(1);
}