Folder Info

Inspect a folder and print its file and folder counts.

Start building, submit solution and get feedback from the community.
2Submit Solution
5 upvotes10 upvotes

Folder Info

You are required to build a CLI tool using Node.js that prints information about a folder.

The tool should inspect the current folder by default. If the user passes a folder path, it should inspect that folder instead.

Here are some example commands you can run to test your CLI:

bash
node folder-info.jsnode folder-info.js srcnode folder-info.js missing-folder

On successful execution, the output should look like this:

txt
Folder: my-projectPath: /Users/you/my-projectFiles: 6Folders: 3

Files is the number of files in the folder, and Folders is the number of subfolders.

If the folder cannot be read, print a friendly error:

txt
error: could not read folder: missing-folder

The error should go to stderr, and the command should set a non-zero exit code.

The goal of this project is to practice reading the current folder, accepting an optional path, and using Node.js to inspect folder contents.

You will need these Node.js APIs:

  • process.cwd() to get the folder where the command started.

  • node:path to resolve a folder path and get the folder name.

  • node:fs/promises to read the folder contents.

Solution

Solution:

js
import { readdir } from 'node:fs/promises';import path from 'node:path';const inputPath = process.argv[2];const folderPath = inputPath ? path.resolve(inputPath) : process.cwd();let entries;try {  entries = await readdir(folderPath, { withFileTypes: true });} catch {  console.error(`error: could not read folder: ${inputPath || folderPath}`);  process.exitCode = 1;}if (entries) {  const fileCount = entries.filter((entry) => entry.isFile()).length;  const folderCount = entries.filter((entry) => entry.isDirectory()).length;  console.log(`Folder: ${path.basename(folderPath)}`);  console.log(`Path: ${folderPath}`);  console.log(`Files: ${fileCount}`);  console.log(`Folders: ${folderCount}`);}

Join the Community

roadmap.sh is the 6th most starred project on GitHub and is visited by hundreds of thousands of developers every month.

Rank  out of 28M!

359K

GitHub Stars

Star us on GitHub
Help us reach #1

+90kevery month

+2.8M

Registered Users

Register yourself
Commit to your growth

+2kevery month

49K

Discord Members

Join on Discord
Join the community

RoadmapsGuidesFAQsYouTube

roadmap.shby@nilbuild

Community created roadmaps, best practices, projects, articles, resources and journeys to help you choose your path and grow in your career.

© roadmap.sh·Terms·Privacy·

ThewNewStack

The top DevOps resource for Kubernetes, cloud-native computing, and large-scale development and deployment.