-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathls.js
More file actions
52 lines (48 loc) · 1.86 KB
/
ls.js
File metadata and controls
52 lines (48 loc) · 1.86 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#!/usr/bin/env node
const fs = require('node:fs');
const path = require('node:path');
function listDirectory(dirPath, showAll, onePerLine) {
try {
const entries = fs.readdirSync(dirPath, { withFileTypes: true });
const filtered = entries.filter((entry) => showAll || !entry.name.startsWith('.'));
if(onePerLine) {
filtered.forEach(entry => console.log(entry.name));
} else {
const names = filtered.map(entry => entry.name);
console.log(names.join(' '));
}
} catch (error) {
console.error(`Error reading directory ${dirPath}: ${error.message}`);
}
}
function main() {
const args = process.argv.slice(2);
// Check for options
const showAll = args.includes('-a');
const onePerLine = args.includes('-1');
//remove options from args
const directories = args.filter(arg => arg !== '-a' && arg !== '-1');
// If no directory is specified, list the current directory
if(directories.length === 0) {
listDirectory(process.cwd(), showAll, onePerLine);
return;
}
//If a directory is specified, list that directory
directories.forEach((arg, index) => {
try {
const stats = fs.statSync(arg);
if(stats.isDirectory()) {
//Print header if multiple directories are listed
if(directories.length > 1) console.log(`${arg}:`);
listDirectory(arg, showAll, onePerLine);
//add a blank line between directory listings if there are multiple directories
if(directories.length > 1 && index < directories.length - 1) console.log('');
} else{
console.log(arg);// single file
}
} catch (error) {
console.error(`Error accessing ${arg}: ${error.message}`);
}
});
}
main();