Skip to content

Commit 9f574ca

Browse files
committed
Add initial implementation of wc command line tool with no options
1 parent 2552f7f commit 9f574ca

3 files changed

Lines changed: 67 additions & 0 deletions

File tree

implement-shell-tools/wc/package-lock.json

Lines changed: 26 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
{
2+
"name": "wc",
3+
"version": "1.0.0",
4+
"description": "You should already be familiar with the `wc` command line tool.",
5+
"main": "wc.mjs",
6+
"type": "module",
7+
"dependencies": {
8+
"commander": "^14.0.3"
9+
},
10+
"scripts": {
11+
"test": "echo \"Error: no test specified\" && exit 1"
12+
},
13+
"keywords": [],
14+
"author": "",
15+
"license": "ISC"
16+
}

implement-shell-tools/wc/wc.mjs

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { program } from 'commander';
2+
import process from 'node:process';
3+
import { promises as fs } from 'node:fs';
4+
5+
program
6+
.name('wc')
7+
.description('Counts the number of lines, words, and characters in a file.')
8+
.argument('<path>', 'The path to the file to analyze')
9+
10+
program.parse();
11+
12+
const argv = program.args;
13+
14+
if (argv.length != 1) {
15+
console.error(
16+
`Expected exactly 1 argument (a path) to be passed but got ${argv.length}.`);
17+
process.exit(1);
18+
}
19+
const path = argv[0];
20+
21+
const content = await fs.readFile(path, 'utf-8');
22+
const lineCount = content.split('\n').filter(Boolean).length;
23+
const wordCount = content.split(' ').filter(Boolean).length;
24+
const characterCount = content.length;
25+
console.log(` ${lineCount} ${wordCount} ${characterCount} ${path}`);

0 commit comments

Comments
 (0)