पाठ 27 / 28

एक छोटा CLI टूल बनाना

argv, fs और shebang को जोड़कर एक चलने योग्य कमांड-लाइन टूल बनाएँ।

एक वर्ड-काउंट CLI

कमांड लाइन पर दिए गए फ़ाइल नाम को पढ़ें और उसके शब्दों की गिनती बताएँ।

#!/usr/bin/env node
import { readFile } from "node:fs/promises";

const filePath = process.argv[2];
if (!filePath) {
  console.error("Usage: wordcount <file>");
  process.exit(1);
}

const text = await readFile(filePath, "utf8");
const words = text.trim().split(/\s+/).length;
console.log(`${filePath}: ${words} words`);

Output:

notes.txt: 42 words

इसे executable बनाना

#!/usr/bin/env node shebang OS को फ़ाइल सीधे चलाने देता है, बिना पहले node टाइप किए।

chmod +x wordcount.js
./wordcount.js notes.txt