|
| 1 | +import { program } from "commander"; |
| 2 | +import { promises as fs } from "node:fs"; |
| 3 | +import process from "node:process"; |
| 4 | + |
| 5 | +program |
| 6 | + .name("myLs") |
| 7 | + .description("my ls clone") |
| 8 | + .option("-l", "line count") |
| 9 | + .option("-w", "words count") |
| 10 | + .option("-c", "character count") |
| 11 | + .option("-s", "character count without spaces") |
| 12 | + .argument("[paths...]", "file or directory paths"); |
| 13 | + |
| 14 | +program.parse(); |
| 15 | + |
| 16 | +const opts = program.opts(); |
| 17 | +let files = program.args; |
| 18 | + |
| 19 | +if (files.length === 0) { |
| 20 | + files = ["."]; |
| 21 | +} |
| 22 | + |
| 23 | +let totalLines = 0; |
| 24 | +let totalWords = 0; |
| 25 | + |
| 26 | +if (opts.l) { |
| 27 | + for (const file of files) { |
| 28 | + const content = await fs.readFile(file, "utf-8"); |
| 29 | + console.log(content); |
| 30 | + const lineCount = content.split("\n").length; |
| 31 | + |
| 32 | + totalLines += lineCount; |
| 33 | + } |
| 34 | + console.log("Lines:", totalLines); |
| 35 | +} |
| 36 | +if (opts.w) { |
| 37 | + for (const file of files) { |
| 38 | + const content = await fs.readFile(file, "utf-8"); |
| 39 | + console.log(content); |
| 40 | + |
| 41 | + const wordCount = content.trim().split(/\s+/).length; |
| 42 | + totalWords += wordCount; |
| 43 | + } |
| 44 | + console.log("Total words:", totalWords); |
| 45 | +} |
| 46 | +if (opts.c) { |
| 47 | + let totalChars = 0; |
| 48 | + for (const file of files) { |
| 49 | + const content = await fs.readFile(file, "utf-8"); |
| 50 | + |
| 51 | + totalChars += content.trim().length; |
| 52 | + // const charList = content.trim().split(/\s+/); |
| 53 | + // for (const char of charList) { |
| 54 | + // totalChars += char.length; |
| 55 | + // } |
| 56 | + } |
| 57 | + console.log("Total characters:", totalChars); |
| 58 | +} |
| 59 | + |
| 60 | +if (opts.s) { |
| 61 | + let totalCharsNoSpaces = 0; |
| 62 | + for (const file of files) { |
| 63 | + const content = await fs.readFile(file, "utf-8"); |
| 64 | + const withoutSpaces = content.replace(/\s/g, ""); |
| 65 | + totalCharsNoSpaces += withoutSpaces.length; |
| 66 | + } |
| 67 | + console.log("Total characters without spaces:", totalCharsNoSpaces); |
| 68 | +} |
0 commit comments