Skip to content

Commit ab2a350

Browse files
committed
Implement node function that works as script shell wc command
1 parent 20f8448 commit ab2a350

3 files changed

Lines changed: 135 additions & 0 deletions

File tree

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

Lines changed: 90 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
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.js",
6+
"scripts": {
7+
"test": "echo \"Error: no test specified\" && exit 1"
8+
},
9+
"keywords": [],
10+
"author": "",
11+
"license": "ISC",
12+
"type": "module",
13+
"dependencies": {
14+
"buffer": "^6.0.3",
15+
"commander": "^14.0.3"
16+
}
17+
}

implement-shell-tools/wc/wc.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
import { program } from 'commander'
2+
import fs from 'fs'
3+
import { Buffer } from 'buffer'
4+
import process from 'process'
5+
program
6+
.command('wc <file>')
7+
.description('File word counts')
8+
.option('-l, --line', 'print the newline counts')
9+
.option('-w, --count', 'print the word counts')
10+
.option('-c, --bytes', 'print the bytes counts')
11+
.action((file, options) => {
12+
const content = fs.readFileSync(`sample-files/${file}`, 'utf-8')
13+
if (options.line) {
14+
console.log(content.split('\n').length)
15+
}
16+
if (options.bytes) {
17+
console.log(Buffer.from(content).toString('hex'))
18+
}
19+
if (options.count) {
20+
console.log(content.split(' ').length)
21+
}
22+
if (options.line && file == '*') {
23+
const files = fs.readdirSync('sample-files/', { withFileTypes: true })
24+
console.log(files)
25+
}
26+
})
27+
28+
program.parse()

0 commit comments

Comments
 (0)