|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import { program } from "commander"; |
| 4 | +import process from "node:process"; |
| 5 | +import { promises as fs } from "node:fs"; |
| 6 | + |
| 7 | +program |
| 8 | + .name("cwc") |
| 9 | + .description("Displays number of lines, words, and bytes in a file") |
| 10 | + .option("-l, --lines", "Counts number of newline characters") |
| 11 | + .option( |
| 12 | + "-w, --words", |
| 13 | + "Counts sequence of characters separated by whitespace", |
| 14 | + ) |
| 15 | + .option("-c, --bytes", "Counts raw size of the files in bytes") |
| 16 | + .argument("<files...>", "File(s) to read and count"); |
| 17 | + |
| 18 | +program.parse(); |
| 19 | + |
| 20 | +const options = program.opts(); |
| 21 | +const files = program.args; |
| 22 | + |
| 23 | +const noFlags = !options.lines && !options.words && !options.bytes; |
| 24 | + |
| 25 | +let totalLines = 0; |
| 26 | +let totalWords = 0; |
| 27 | +let totalBytes = 0; |
| 28 | + |
| 29 | +async function countFiles(file) { |
| 30 | + try { |
| 31 | + const buffer = await fs.readFile(file); |
| 32 | + const content = buffer.toString("utf-8"); |
| 33 | + |
| 34 | + const lineCount = content === "" ? 0 : content.split("\n").length - 1; |
| 35 | + const wordCount = content.trim() ? content.trim().split(/\s+/).length : 0; |
| 36 | + const byteCount = buffer.length; |
| 37 | + |
| 38 | + totalLines += lineCount; |
| 39 | + totalWords += wordCount; |
| 40 | + totalBytes += byteCount; |
| 41 | + |
| 42 | + let result = ""; |
| 43 | + |
| 44 | + if (options.lines || noFlags) result += `${String(lineCount).padStart(8)}`; |
| 45 | + if (options.words || noFlags) result += `${String(wordCount).padStart(8)}`; |
| 46 | + if (options.bytes || noFlags) result += `${String(byteCount).padStart(8)}`; |
| 47 | + |
| 48 | + process.stdout.write(`${result} ${file}\n`); |
| 49 | + } catch (error) { |
| 50 | + console.error(`cwc: ${file}: ${error.message}`); |
| 51 | + process.exit(1); |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +(async () => { |
| 56 | + for (const file of files) { |
| 57 | + await countFiles(file); |
| 58 | + } |
| 59 | + |
| 60 | + if (files.length > 1) { |
| 61 | + let total = ""; |
| 62 | + |
| 63 | + if (options.lines || noFlags) total += `${String(totalLines).padStart(8)}`; |
| 64 | + if (options.words || noFlags) total += `${String(totalWords).padStart(8)}`; |
| 65 | + if (options.bytes || noFlags) total += `${String(totalBytes).padStart(8)}`; |
| 66 | + |
| 67 | + process.stdout.write(`${total} total\n`); |
| 68 | + } |
| 69 | +})(); |
0 commit comments