NodeJS Program to List Directory Files with Explanation
NodeJS
Hard
File System & Paths
35 views
1 min read
80 words
This problem helps you practice core NodeJS fundamentals in a practical way. It builds intuition around directory, file, path. Let’s break it down step by step so you can implement it confidently.
Problem Statement
Read a directory path and print file names sorted.
Input Format
stdin: directory path.
Output Format
Print one file per line.
Constraints
Ignore subfolders.
Code Solution
This explanation is written for learning purposes and to help beginners understand the concept clearly.
const fs = require('fs');
const path = require('path');
const dir = fs.readFileSync(0, 'utf8').trim();
if (!dir) process.exit(0);
try {
const names = fs.readdirSync(dir, { withFileTypes: true })
.filter((d) => d.isFile())
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b));
process.stdout.write(names.join('\
'));
} catch (e) {
console.log('NOT FOUND');
}
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Solution Guide
Problem
Read a directory path and print file names sorted.
Input / Output
Input
stdin: directory path.
Output
Print one file per line.
Constraints
Ignore subfolders.
Details
Common Mistakes
- Misreading input/output format.
- Not handling constraints and edge cases.
- Off-by-one errors in loops.
- Forgetting to reset variables between test cases (if any).
Official Solution
const fs = require('fs');
const path = require('path');
const dir = fs.readFileSync(0, 'utf8').trim();
if (!dir) process.exit(0);
try {
const names = fs.readdirSync(dir, { withFileTypes: true })
.filter((d) => d.isFile())
.map((d) => d.name)
.sort((a, b) => a.localeCompare(b));
process.stdout.write(names.join('\
'));
} catch (e) {
console.log('NOT FOUND');
}
Solutions (0)
No solutions submitted yet. Be the first!