使用NodeJS与FS模块获取目录信息及文件length的技术咨询
Hey Liam, let's work through your two Node.js + fs module questions with practical, straightforward solutions!
For this task, we can use Node.js's fs.promises API (modern, promise-based, avoids callback hell) along with path to handle file paths cleanly. The example below will scan a target directory, list all its direct subdirectories, and count how many items (files + subdirectories) are inside each one:
const fs = require('fs').promises; const path = require('path'); async function getDirectoryItemCounts(rootDir = './') { try { // Read all items in the root directory, with file type metadata const directoryItems = await fs.readdir(rootDir, { withFileTypes: true }); // Filter to keep only directories const subdirectories = directoryItems.filter(item => item.isDirectory()); const directoryInfo = []; for (const dir of subdirectories) { const fullDirPath = path.join(rootDir, dir.name); // Count all items in the current subdirectory const dirContents = await fs.readdir(fullDirPath); directoryInfo.push({ directoryName: dir.name, totalItems: dirContents.length }); } return directoryInfo; } catch (error) { console.error('Failed to read directories:', error); throw error; } } // Usage example: getDirectoryItemCounts('./your-target-dir').then(console.log);
If you need to include nested directories (not just direct children), you can extend this with a recursive function—just let me know if you want that variant!
.length (or Find Directory with Most Files) First, let's clarify: when you say .length for filenames, I assume you mean the character length of the filename string. If you actually want the file's byte size (similar to a "length" for the file's content), I'll cover that too.
Option 1: Simple List of Filenames + Name Lengths
This uses the same promise-based API to quickly generate your list:
async function getFilenamesAndNameLengths(rootDir = './') { try { const items = await fs.readdir(rootDir, { withFileTypes: true }); const files = items.filter(item => item.isFile()); // Map each file to an object with its name and name length return files.map(file => ({ fileName: file.name, nameLength: file.name.length })); } catch (error) { console.error('Failed to read files:', error); throw error; } } // Usage example: getFilenamesAndNameLengths('./').then(console.log);
Option 2: Filenames + File Byte Size (If That's What You Mean by .length)
If you need the size of the file content instead of the filename length, use fs.stat to fetch file metadata:
async function getFilenamesAndFileSizes(rootDir = './') { try { const items = await fs.readdir(rootDir, { withFileTypes: true }); const files = items.filter(item => item.isFile()); const fileDetails = []; for (const file of files) { const filePath = path.join(rootDir, file.name); const fileStats = await fs.stat(filePath); fileDetails.push({ fileName: file.name, fileSizeBytes: fileStats.size // This is the "length" of the file content }); } return fileDetails; } catch (error) { console.error('Failed to fetch file details:', error); throw error; } }
If You Only Need the Directory with the Most Files
If generating the full list isn't necessary, here's a recursive solution to find which directory (including nested ones) has the most files:
async function findDirectoryWithMostFiles(rootDir = './') { let maxFileCount = 0; let topDirectory = ''; // Recursive helper to scan all directories async function scanDirectory(currentDir) { const items = await fs.readdir(currentDir, { withFileTypes: true }); const fileCount = items.filter(item => item.isFile()).length; // Update our tracking variables if this directory has more files if (fileCount > maxFileCount) { maxFileCount = fileCount; topDirectory = currentDir; } // Scan all subdirectories const subDirs = items.filter(item => item.isDirectory()); for (const subDir of subDirs) { await scanDirectory(path.join(currentDir, subDir.name)); } } await scanDirectory(rootDir); return { directoryPath: topDirectory, fileCount: maxFileCount }; } // Usage example: findDirectoryWithMostFiles('./').then(console.log);
All these solutions use native Node.js APIs—no external packages needed, which keeps things simple and lightweight.
内容的提问来源于stack exchange,提问作者Liam Shackhorn

