Working with Directories
We've learned many file manipulation techniques throughout our exploration of the FileSystem (fs
) module. But directories are more than places to store files - they offer opportunities for organization, data analysis, and more.
In this chapter, we'll dive into directory manipulation and guide you on navigating directories, gathering vital statistics, processing directories, and creating a script to analyze and display directory contents.
📂 Navigating Directories with fs.readdir
The fs.readdir
method asynchronously reads the contents of a directory. It returns an array of filenames. This method can be beneficial for task listing files in a folder.
Consider a scenario where we deal with extensive legal contracts, briefs, and other documents related to different cases and clients. We could create a system that extracts and lists the names of the files within each client's folder.
Code Example: Read the file names of a directory
const fs = require("fs").promises;async function listDirectoryContents(directoryPath) {try {const files = await fs.readdir(directoryPath);console.log("Directory Contents:", files);} catch (err) {console.error("Error reading directory:", err.message);}}listDirectoryContents("./docs");
Step by Step Explanation
📊 Obtaining Directories Statistics with fs.stat
Directories house files and hold valuable information about each file's attributes.
The fs.stat
method asynchronously retrieves the stats of a file or directory. These stats include file size, permissions, timestamps, and more.
Let's obtain the statistics of each folder inside the docs folder.
Code Example: Get directories names and statistics
const fs = require("fs").promises;async function processDirectoryContents(directoryPath) {try {const files = await fs.readdir(directoryPath);const fileStatsPromises = files.map(async (file) => {const filePath = `${directoryPath}/${file}`;const stats = await fs.stat(filePath);return { name: file, stats };});const fileStats = await Promise.all(fileStatsPromises);console.log("Detailed File Information:", fileStats);} catch (err) {console.error("Error processing directory contents:", err.message);}}processDirectoryContents("./docs");
Step by Step Explanation
🧐 Quiz Time
Let's put your knowledge of the FileSystem (fs
) module to the test with a few questions related to directory manipulation.
Obrigado pelo seu feedback!