UNPKG

varun-word-counter-cli

Version:

A CLI tool to count words in a text file

68 lines (55 loc) • 1.78 kB
#!/usr/bin/env node 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); }