|
| 1 | +import process, { exit } from "node:process"; |
| 2 | +import fs from "node:fs"; |
| 3 | + |
| 4 | +const argv = process.argv.slice(2); |
| 5 | + |
| 6 | +const showWords = argv.includes("-w"); |
| 7 | +const showLines = argv.includes("-l"); |
| 8 | +const showBytes = argv.includes("-c"); |
| 9 | +const showCharacters = argv.includes("-m"); |
| 10 | + |
| 11 | +// filter flags, and getting the string of filename |
| 12 | +const filePaths = argv.filter((arg) => !arg.startsWith("-")); |
| 13 | + |
| 14 | +const noFlags = !showLines && !showCharacters && !showWords && !showCharacters; |
| 15 | +if (!filePaths) { |
| 16 | + console.error("PLease provide a file path"); |
| 17 | + process.exit(1); |
| 18 | +} |
| 19 | +// loop trough the array to get each file path. |
| 20 | +filePaths.forEach((filePath) => { |
| 21 | + const content = fs.readFileSync(filePath, "utf-8"); |
| 22 | + |
| 23 | + const lines = content.split("\n").length - 1; |
| 24 | + const words = content |
| 25 | + .trim() |
| 26 | + .split(/\s+/) |
| 27 | + .filter((word) => word != "").length; |
| 28 | + // here I used Buffer.byteLength even if characters and bytes can be the same number .length, however sometimes an emoji or special characters can be heavier 2b or 4b |
| 29 | + const bytes = Buffer.byteLength(content); |
| 30 | + const characters = content.length; |
| 31 | + |
| 32 | + let output = ""; |
| 33 | + |
| 34 | + if (showLines || noFlags) output += `${lines} `; |
| 35 | + if (showWords || noFlags) output += `${words} `; |
| 36 | + if (showBytes || noFlags) output += `${bytes} `; |
| 37 | + if (showCharacters || noFlags) output += `${characters} `; |
| 38 | + |
| 39 | + console.log(`${output} ${filePath}`); |
| 40 | +}); |
0 commit comments