|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +const fs = require("fs"); |
| 4 | +const path = require("path"); |
| 5 | + |
| 6 | +// -------- args parsing -------- |
| 7 | +const args = process.argv.slice(2); |
| 8 | + |
| 9 | +let onePerLine = false; // -1 |
| 10 | +let showAll = false; // -a |
| 11 | +let targets = []; |
| 12 | + |
| 13 | +for (const arg of args) { |
| 14 | + if (arg === "-1") onePerLine = true; |
| 15 | + else if (arg === "-a") showAll = true; |
| 16 | + else targets.push(arg); |
| 17 | +} |
| 18 | + |
| 19 | +// Coursework only tests -1 variants, so enforce it clearly |
| 20 | +if (!onePerLine) { |
| 21 | + console.error("Usage: node ls.js -1 [-a] [path]"); |
| 22 | + process.exit(1); |
| 23 | +} |
| 24 | + |
| 25 | +if (targets.length === 0) targets = ["."]; |
| 26 | +if (targets.length > 1) { |
| 27 | + console.error("ls.js: only one path is supported in this exercise"); |
| 28 | + process.exit(1); |
| 29 | +} |
| 30 | + |
| 31 | +const target = targets[0]; |
| 32 | + |
| 33 | +// -------- helpers -------- |
| 34 | +function sortLikeLs(names) { |
| 35 | + return names.sort((a, b) => a.localeCompare(b)); |
| 36 | +} |
| 37 | + |
| 38 | +function listDir(dirPath) { |
| 39 | + let entries; |
| 40 | + try { |
| 41 | + entries = fs.readdirSync(dirPath, { withFileTypes: false }); |
| 42 | + } catch (err) { |
| 43 | + console.error(`ls.js: cannot access '${dirPath}': ${err.message}`); |
| 44 | + process.exit(1); |
| 45 | + } |
| 46 | + |
| 47 | + // readdirSync does NOT include "." and ".." — ls -a does. |
| 48 | + if (showAll) { |
| 49 | + // keep dotfiles + add . and .. |
| 50 | + entries = [".", "..", ...entries]; |
| 51 | + } else { |
| 52 | + // hide dotfiles |
| 53 | + entries = entries.filter((name) => !name.startsWith(".")); |
| 54 | + } |
| 55 | + |
| 56 | + entries = sortLikeLs(entries); |
| 57 | + |
| 58 | + // -1 => one per line |
| 59 | + for (const name of entries) { |
| 60 | + process.stdout.write(name + "\n"); |
| 61 | + } |
| 62 | +} |
| 63 | + |
| 64 | +function listFile(filePath) { |
| 65 | + // ls -1 file => prints the file name |
| 66 | + process.stdout.write(path.basename(filePath) + "\n"); |
| 67 | +} |
| 68 | + |
| 69 | +// -------- main -------- |
| 70 | +let stat; |
| 71 | +try { |
| 72 | + stat = fs.statSync(target); |
| 73 | +} catch (err) { |
| 74 | + console.error(`ls.js: cannot access '${target}': ${err.message}`); |
| 75 | + process.exit(1); |
| 76 | +} |
| 77 | + |
| 78 | +if (stat.isDirectory()) listDir(target); |
| 79 | +else listFile(target); |
0 commit comments