Skip to content

Commit b75b9f7

Browse files
committed
Implementation of ls with -a -1 options
1 parent e226c94 commit b75b9f7

3 files changed

Lines changed: 75 additions & 0 deletions

File tree

implement-shell-tools/ls/ls.mjs

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
import { program } from 'commander';
2+
import process from 'node:process';
3+
import { promises as fs } from 'node:fs';
4+
5+
program
6+
.name('ls')
7+
.description('Lists the contents of a directory.')
8+
.argument('[path]', 'The path to the directory to list, defaults to the current directory')
9+
.option('-a, --all', 'Do not ignore entries starting with .')
10+
.option('-1', 'List one file per line');
11+
12+
program.parse();
13+
14+
const argv = program.args;
15+
const path = argv[0] || '.';
16+
17+
let showAll = program.opts().all || false;
18+
let onePerLine = program.opts()['1'] || false;
19+
20+
try {
21+
const files = await fs.readdir(path);
22+
files.sort((a, b) => a.localeCompare(b, undefined, { numeric: true, sensitivity: 'base' }));
23+
for (const file of files) {
24+
if (showAll || !file.startsWith('.')) {
25+
if (onePerLine) {
26+
process.stdout.write(`${file}\n`);
27+
} else {
28+
process.stdout.write(`${file} `);
29+
}
30+
}
31+
}
32+
} catch (err) {
33+
process.stderr.write(`cannot access '${path}': No such file or directory\n`);
34+
process.exit(1);
35+
}

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

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

0 commit comments

Comments
 (0)