|
| 1 | + |
| 2 | +import { program } from "commander"; |
| 3 | +import { promises as fs } from "node:fs"; |
| 4 | + |
| 5 | +program |
| 6 | + .option("-l", "Print only the line count") |
| 7 | + .option("-w", "Print only the word count") |
| 8 | + .option("-c", "Print only the byte count") |
| 9 | + .argument("<paths...>", "One or more file paths"); |
| 10 | + |
| 11 | +program.parse(); |
| 12 | + |
| 13 | +const opts = program.opts(); |
| 14 | +const paths = program.args; |
| 15 | + |
| 16 | +async function wcFile(path) { |
| 17 | + const content = await fs.readFile(path, "utf8"); |
| 18 | + |
| 19 | + const lines = content.split("\n").length; |
| 20 | + const words = content.trim().split(/\s+/).filter(Boolean).length; |
| 21 | + const bytes = Buffer.byteLength(content, "utf8"); |
| 22 | + |
| 23 | + return { lines, words, bytes }; |
| 24 | +} |
| 25 | + |
| 26 | +function formatOutput(counts, filename, opts) { |
| 27 | + if (opts.l) return `${counts.lines} ${filename}`; |
| 28 | + if (opts.w) return `${counts.words} ${filename}`; |
| 29 | + if (opts.c) return `${counts.bytes} ${filename}`; |
| 30 | + |
| 31 | + return `${counts.lines} ${counts.words} ${counts.bytes} ${filename}`; |
| 32 | +} |
| 33 | + |
| 34 | +async function main() { |
| 35 | + let total = { lines: 0, words: 0, bytes: 0 }; |
| 36 | + let multipleFiles = paths.length > 1; |
| 37 | + |
| 38 | + for (const path of paths) { |
| 39 | + const counts = await wcFile(path); |
| 40 | + |
| 41 | + total.lines += counts.lines; |
| 42 | + total.words += counts.words; |
| 43 | + total.bytes += counts.bytes; |
| 44 | + |
| 45 | + console.log(formatOutput(counts, path, opts)); |
| 46 | + } |
| 47 | + |
| 48 | + if (multipleFiles) { |
| 49 | + console.log(formatOutput(total, "total", opts)); |
| 50 | + } |
| 51 | +} |
| 52 | + |
| 53 | +main(); |
0 commit comments