Skip to content

Commit 8ae903a

Browse files
committed
wc-implementation
1 parent f78e378 commit 8ae903a

File tree

1 file changed

+38
-0
lines changed
  • implement-shell-tools/wc

1 file changed

+38
-0
lines changed

implement-shell-tools/wc/wc.js

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
import { program } from "commander";
2+
import { promises as fs } from "node:fs";
3+
4+
program
5+
.name("wc")
6+
.description("Custom wc CLI - count lines, words, bytes")
7+
.argument("<file>", "File to process")
8+
.option("-l", "Print the number of lines")
9+
.option("-w", "Print the number of words")
10+
.option("-c", "Print the number of bytes")
11+
.parse();
12+
13+
const options = program.opts();
14+
const filePath = program.args[0];
15+
16+
try {
17+
const data = await fs.readFile(filePath,"utf-8");
18+
19+
20+
21+
const lineCount = data.split("\n").length;
22+
const wordCount = data.trim().split(/\s+/).length;
23+
const byteCount = data.length;
24+
25+
const showAll = !options.l && !options.w && !options.c;
26+
27+
28+
const output = [];
29+
if (options.l || showAll) output.push(lineCount.toString().padStart(8));
30+
if (options.w || showAll) output.push(wordCount.toString().padStart(8));
31+
if (options.c || showAll) output.push(byteCount.toString().padStart(8));
32+
output.push(filePath);
33+
34+
console.log(output.join(" "));
35+
} catch (err) {
36+
console.error(`Error reading file "${filePath}":`, err.message);
37+
process.exit(1);
38+
}

0 commit comments

Comments
 (0)