|
1 | | -// Power shell commands =======> Vs <===== Js codes |
2 | | - |
3 | | -// wc sample-files/* |
| 1 | +// Power shell commands with Js codes |
4 | 2 |
|
5 | 3 | const fs = require("fs"); |
6 | | -const filePath = "./sample-files"; |
7 | | -const contents = fs.readdirSync(filePath); |
| 4 | +const args = process.argv.slice(2); |
| 5 | + |
| 6 | +let flags = []; |
| 7 | +let paths = []; |
| 8 | + |
| 9 | +// Check arguments: separate flags and paths |
| 10 | +args.forEach((arg) => { |
| 11 | + if (arg.startsWith("-")) { |
| 12 | + flags.push(arg); |
| 13 | + } else { |
| 14 | + paths.push(arg); |
| 15 | + } |
| 16 | +}); |
8 | 17 |
|
9 | 18 | let totalLines = 0; |
10 | 19 | let totalWords = 0; |
11 | 20 | let totalCharacters = 0; |
12 | 21 |
|
13 | | -contents.forEach((file) => { |
14 | | - const path = `${filePath}/${file}`; |
| 22 | +paths.forEach((file) => { |
| 23 | + const content = fs.readFileSync(file, "utf-8"); |
| 24 | + |
| 25 | + const lines = content.split("\n").length - 1; |
| 26 | + const words = content.trim().split(/\s+/).length; |
| 27 | + const chars = content.length; |
| 28 | + |
| 29 | + if (flags.length === 0) { |
| 30 | + console.log(lines, words, chars, file); |
| 31 | + } else { |
| 32 | + let output = []; |
15 | 33 |
|
16 | | - const files = fs.readFileSync(path, "utf-8"); |
| 34 | + if (flags.includes("-l")) { |
| 35 | + output.push(lines); |
| 36 | + } |
17 | 37 |
|
18 | | - const lines = files.split("\n").length - 1; |
19 | | - const words = files.trim().split(/\s+/).length; |
20 | | - const chars = files.length; |
| 38 | + if (flags.includes("-w")) { |
| 39 | + output.push(words); |
| 40 | + } |
21 | 41 |
|
22 | | - console.log(lines, words, chars, path); |
| 42 | + if (flags.includes("-c")) { |
| 43 | + output.push(chars); |
| 44 | + } |
| 45 | + |
| 46 | + console.log(...output, file); |
| 47 | + } |
23 | 48 |
|
24 | 49 | totalLines += lines; |
25 | 50 | totalWords += words; |
26 | 51 | totalCharacters += chars; |
27 | 52 | }); |
28 | | -console.log(totalLines, totalWords, totalCharacters, "total"); |
| 53 | +if (paths.length > 1) { |
| 54 | + let totalOutput = []; |
| 55 | + |
| 56 | + if (flags.length === 0) { |
| 57 | + totalOutput.push(totalLines, totalWords, totalCharacters); |
| 58 | + } else { |
| 59 | + if (flags.includes("-l")) { |
| 60 | + totalOutput.push(totalLines); |
| 61 | + } |
| 62 | + |
| 63 | + if (flags.includes("-w")) { |
| 64 | + totalOutput.push(totalWords); |
| 65 | + } |
| 66 | + |
| 67 | + if (flags.includes("-c")) { |
| 68 | + totalOutput.push(totalCharacters); |
| 69 | + } |
| 70 | + } |
| 71 | + |
| 72 | + console.log(...totalOutput, "total"); |
| 73 | +} |
0 commit comments