Conteúdo do Curso
Node.js Express: API & CLI Apps
4. Developing REST API
Node.js Express: API & CLI Apps
Console App: DirInspect Pro
This chapter presents you with a challenge: creating an advanced console app named DirInspect Pro. This app will empower you to thoroughly analyze any directory and gain insightful statistics about its files and subdirectories.
🏆 Challenge Awaits
Picture a scenario where you must navigate a labyrinth of folders containing crucial files and data. DirInspect Pro is your ally in this journey, providing comprehensive insights into the directory's structure and contents.
🚀 The Resulting App
Get ready to wield DirInspect Pro's capabilities. The app will furnish you with critical information, such as
- The total number of items;
- The aggregate size of all items;
- The largest file's name and size;
- The detailed list of individual file names and sizes.
App in Action
DirInspect Pro's Output:
Two Paths to Choose
You have two paths ahead.
- The first is to tackle this challenge head-on, honing your skills without guidance;
- The second is to follow a helpful guide that guarantees your success.
Whichever path you choose, you're in for a rewarding journey culminating in creating a captivating and functional console app.
Step 1: Import Required Modules
To embark on this adventure, you'll need the right tools. Begin by importing two key modules: fs.promises
to manage the file system asynchronously and path
to handle file paths effectively.
Code Description
fs
module. The
fs
module provides functions for interacting with the file
system in a Node.js environment. The .promises
property is used
here to access the promises-based API of the fs
module, which
allows asynchronous file operations to be written in a more modern and
readable manner using async/await
syntax. Line 2: Imports the built-in
path
module. The
path
module provides utilities for working with file and directory paths. It's
used to handle file path manipulation, normalization, and more.
Step 2: Define getStats Function
The asynchronous function, getStats
, takes a file or directory path as an argument and attempts to retrieve its statistics using fs.stat
.
- If successful, it returns the statistics;
- If an error occurs, it logs an error message and returns
null
.
Code Description
getStats
that takes a single parameter
filePath
.Lines 2, 5: This structure is a try-catch block used for error handling. The code within the
try
block attempts to execute,
and if any errors occur, they are caught and handled within the
catch
block. Line 3: Inside the
try
block, this line uses the
await
keyword to asynchronously call the
fs.stat(filePath)
method. The fs.stat()
method
retrieves information about the specified file path, including details like
size, creation time, and more. The await
keyword ensures that
the asynchronous operation is completed before moving on. Line 4: If the
fs.stat()
operation is successful, the
stats
object containing file information is returned. Line 6: If an error occurs during the
fs.stat()
operation, the catch block is executed. This line
logs an error message along with the error's message to the console using
console.error()
. Line 7: If an error occurs, the function returns
null
to
indicate that the file stats could not be retrieved successfully.
Step 3: Define analyzeFile Function
The analyzeFile
function uses the getStats
function to obtain statistics for a file. If statistics are available (not null
), it returns an object containing the file's name (extracted using path.basename
) and its size.
Code Description
analyzeFile
that takes a single parameter
filePath
. Line 2: Inside the function, this line uses the
await
keyword to asynchronously call the
getStats(filePath)
function. This retrieves the file stats for
the provided filePath
. Line 3: After obtaining the file stats, this line checks if stats is falsy (
null
, undefined
, etc.). If it is, the
function returns null
immediately. This ensures that if there's
an issue getting the stats, the function won't proceed further. Line 5-8: If the file stats were successfully obtained and not null, this line constructs an object containing the file's name and size. It uses the
path.basename(filePath)
function to extract the filename
from the full path and uses stats.size
to include the file size
in bytes. Step 4: Define analyzeDirectory Function
The analyzeDirectory
function takes a directory path as an argument and comprehensively analyzes its contents.
- It begins by reading the items within the directory using
fs.readdir
and then iterates through each item; - For each item, it constructs the full path using
path.join
and retrieves its statistics using thegetStats
function; - If the
stats
indicate that the item is a file, it updates file-related statistics; - If the item is a subdirectory, it recursively calls the
analyzeDirectory
function to analyze its contents and then aggregates the statistics.
Code Description
analyzeDirectory
that takes a single parameter
directoryPath
. Line 3: Inside the function, this line uses the
await
keyword to asynchronously call the
fs.readdir(directoryPath)
method. This retrieves an array of
items (files and subdirectories) within the specified directory. Lines 4-8: These lines declare variables to keep track of various statistics related to the directory and its contents.
Line 10: This
for
loop iterates over each item in the
items array, which represents the contents of the directory. Line 11: Inside the loop, this line constructs the full path to the current item by joining the
directoryPath
and
item
using path.join()
. This is used to get the
full path to each item within the directory. Line 12: This line asynchronously retrieves file stats for the current item using the
getStats
function. Line 13: If there's an issue getting the stats for the current item, this line skips to the next iteration of the loop using
continue
. Lines 17-37: These conditional statements check if the current item is a file or a directory based on its stats.
- If it's a file, statistics are updated:
totalFiles
and totalSize
are incremented, the
largest file is updated if necessary, and the file is added to the
fileList
. - If it's a directory, the
analyzeDirectory
function is called recursively for the
subdirectory. The statistics of the subdirectory are then accumulated and
merged with the current directory's statistics. Lines 40-46: After analyzing all items within the directory, this line constructs and returns an object containing various statistics about the directory and its contents.
Lines 47-56: If any errors occur during the process of analyzing the directory, this
catch
block is executed. It logs an error
message and returns default values for the statistics.
Step 5: Define main Function and Invoke
The main
function is the entry point of the script. It specifies the directory path to analyze (in this case, ./docs
), calls the analyzeDirectory
function to obtain the statistics of the directory and its contents, and then outputs the collected information.
The function prints out
- The total number of items;
- The total number of files;
- The total size;
- The details about the largest file;
- The list of files in the directory.
Code Description
Line 2: This line defines the
directoryPath
variable,
which holds the path to the directory that will be analyzed. In this case,
it's set to "./docs", which is a relative path. Line 3: This line calls the
analyzeDirectory
function
with the provided directoryPath
and uses the
await
keyword to asynchronously wait for the result. The result
is stored in the directoryStats
variable. Lines 5-17: These lines use
console.log()
to display
various information about the analyzed directory and its contents. It prints
the total number of items, total number of files, total size in bytes, and
details about the largest file. Lines 18-20: This
for
loop iterates over each file
object in the fileList
array within the
directoryStats
object. - This line logs information about each file, including its name and size in bytes.
Line 23: Finally, this line calls the
main
function to
start the analysis process.
🎉 Conclusion: Mastered Skills
With DirInspect Pro, you've mastered the art of analyzing directories like a pro. This console app showcases your ability to extract file statistics, handle errors seamlessly, and unveil meaningful insights about files and subdirectories within a specified directory.
👨💻 Full App Code
Tudo estava claro?
Conteúdo do Curso
Node.js Express: API & CLI Apps
4. Developing REST API
Node.js Express: API & CLI Apps
Console App: DirInspect Pro
This chapter presents you with a challenge: creating an advanced console app named DirInspect Pro. This app will empower you to thoroughly analyze any directory and gain insightful statistics about its files and subdirectories.
🏆 Challenge Awaits
Picture a scenario where you must navigate a labyrinth of folders containing crucial files and data. DirInspect Pro is your ally in this journey, providing comprehensive insights into the directory's structure and contents.
🚀 The Resulting App
Get ready to wield DirInspect Pro's capabilities. The app will furnish you with critical information, such as
- The total number of items;
- The aggregate size of all items;
- The largest file's name and size;
- The detailed list of individual file names and sizes.
App in Action
DirInspect Pro's Output:
Two Paths to Choose
You have two paths ahead.
- The first is to tackle this challenge head-on, honing your skills without guidance;
- The second is to follow a helpful guide that guarantees your success.
Whichever path you choose, you're in for a rewarding journey culminating in creating a captivating and functional console app.
Step 1: Import Required Modules
To embark on this adventure, you'll need the right tools. Begin by importing two key modules: fs.promises
to manage the file system asynchronously and path
to handle file paths effectively.
Code Description
fs
module. The
fs
module provides functions for interacting with the file
system in a Node.js environment. The .promises
property is used
here to access the promises-based API of the fs
module, which
allows asynchronous file operations to be written in a more modern and
readable manner using async/await
syntax. Line 2: Imports the built-in
path
module. The
path
module provides utilities for working with file and directory paths. It's
used to handle file path manipulation, normalization, and more.
Step 2: Define getStats Function
The asynchronous function, getStats
, takes a file or directory path as an argument and attempts to retrieve its statistics using fs.stat
.
- If successful, it returns the statistics;
- If an error occurs, it logs an error message and returns
null
.
Code Description
getStats
that takes a single parameter
filePath
.Lines 2, 5: This structure is a try-catch block used for error handling. The code within the
try
block attempts to execute,
and if any errors occur, they are caught and handled within the
catch
block. Line 3: Inside the
try
block, this line uses the
await
keyword to asynchronously call the
fs.stat(filePath)
method. The fs.stat()
method
retrieves information about the specified file path, including details like
size, creation time, and more. The await
keyword ensures that
the asynchronous operation is completed before moving on. Line 4: If the
fs.stat()
operation is successful, the
stats
object containing file information is returned. Line 6: If an error occurs during the
fs.stat()
operation, the catch block is executed. This line
logs an error message along with the error's message to the console using
console.error()
. Line 7: If an error occurs, the function returns
null
to
indicate that the file stats could not be retrieved successfully.
Step 3: Define analyzeFile Function
The analyzeFile
function uses the getStats
function to obtain statistics for a file. If statistics are available (not null
), it returns an object containing the file's name (extracted using path.basename
) and its size.
Code Description
analyzeFile
that takes a single parameter
filePath
. Line 2: Inside the function, this line uses the
await
keyword to asynchronously call the
getStats(filePath)
function. This retrieves the file stats for
the provided filePath
. Line 3: After obtaining the file stats, this line checks if stats is falsy (
null
, undefined
, etc.). If it is, the
function returns null
immediately. This ensures that if there's
an issue getting the stats, the function won't proceed further. Line 5-8: If the file stats were successfully obtained and not null, this line constructs an object containing the file's name and size. It uses the
path.basename(filePath)
function to extract the filename
from the full path and uses stats.size
to include the file size
in bytes. Step 4: Define analyzeDirectory Function
The analyzeDirectory
function takes a directory path as an argument and comprehensively analyzes its contents.
- It begins by reading the items within the directory using
fs.readdir
and then iterates through each item; - For each item, it constructs the full path using
path.join
and retrieves its statistics using thegetStats
function; - If the
stats
indicate that the item is a file, it updates file-related statistics; - If the item is a subdirectory, it recursively calls the
analyzeDirectory
function to analyze its contents and then aggregates the statistics.
Code Description
analyzeDirectory
that takes a single parameter
directoryPath
. Line 3: Inside the function, this line uses the
await
keyword to asynchronously call the
fs.readdir(directoryPath)
method. This retrieves an array of
items (files and subdirectories) within the specified directory. Lines 4-8: These lines declare variables to keep track of various statistics related to the directory and its contents.
Line 10: This
for
loop iterates over each item in the
items array, which represents the contents of the directory. Line 11: Inside the loop, this line constructs the full path to the current item by joining the
directoryPath
and
item
using path.join()
. This is used to get the
full path to each item within the directory. Line 12: This line asynchronously retrieves file stats for the current item using the
getStats
function. Line 13: If there's an issue getting the stats for the current item, this line skips to the next iteration of the loop using
continue
. Lines 17-37: These conditional statements check if the current item is a file or a directory based on its stats.
- If it's a file, statistics are updated:
totalFiles
and totalSize
are incremented, the
largest file is updated if necessary, and the file is added to the
fileList
. - If it's a directory, the
analyzeDirectory
function is called recursively for the
subdirectory. The statistics of the subdirectory are then accumulated and
merged with the current directory's statistics. Lines 40-46: After analyzing all items within the directory, this line constructs and returns an object containing various statistics about the directory and its contents.
Lines 47-56: If any errors occur during the process of analyzing the directory, this
catch
block is executed. It logs an error
message and returns default values for the statistics.
Step 5: Define main Function and Invoke
The main
function is the entry point of the script. It specifies the directory path to analyze (in this case, ./docs
), calls the analyzeDirectory
function to obtain the statistics of the directory and its contents, and then outputs the collected information.
The function prints out
- The total number of items;
- The total number of files;
- The total size;
- The details about the largest file;
- The list of files in the directory.
Code Description
Line 2: This line defines the
directoryPath
variable,
which holds the path to the directory that will be analyzed. In this case,
it's set to "./docs", which is a relative path. Line 3: This line calls the
analyzeDirectory
function
with the provided directoryPath
and uses the
await
keyword to asynchronously wait for the result. The result
is stored in the directoryStats
variable. Lines 5-17: These lines use
console.log()
to display
various information about the analyzed directory and its contents. It prints
the total number of items, total number of files, total size in bytes, and
details about the largest file. Lines 18-20: This
for
loop iterates over each file
object in the fileList
array within the
directoryStats
object. - This line logs information about each file, including its name and size in bytes.
Line 23: Finally, this line calls the
main
function to
start the analysis process.
🎉 Conclusion: Mastered Skills
With DirInspect Pro, you've mastered the art of analyzing directories like a pro. This console app showcases your ability to extract file statistics, handle errors seamlessly, and unveil meaningful insights about files and subdirectories within a specified directory.
👨💻 Full App Code
Tudo estava claro?