MeetCode - Programming Platform | MeetCode - Programming Solutions Platform

NodeJS Program to List Directory Files with Explanation

NodeJS Hard File System & Paths 35 views
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.
Back to Questions

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'); }

Output Example

Input:
./
Output:
(names)

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).

Notes & Extra Practice

Solutions (0)

No solutions submitted yet. Be the first!

Prev Next