如何修改Node.js代码统计当前目录下仅文件的数量(不含文件夹)
Count Only Files (Not Folders) in a Directory with Node.js
Got it, let's fix your code so it only counts actual files—your original snippet counts every entry in the directory, which includes both files and folders. Here's how to adjust it properly:
Option 1: Callback-Based Approach (Traditional)
This uses the standard callback pattern and checks each entry's status to determine if it's a file:
const fs = require('fs'); const path = require('path'); fs.readdir(process.cwd(), function(err, entries) { if (err) { console.error('Failed to read directory:', err); return; } let fileCount = 0; let processedEntries = 0; entries.forEach(entry => { const fullPath = path.join(process.cwd(), entry); // Use lstat instead of stat to avoid following symlinks (use stat if you want to follow them) fs.lstat(fullPath, function(err, stats) { if (err) { console.error(`Error checking entry "${entry}":`, err); processedEntries++; return; } if (stats.isFile()) { fileCount++; } processedEntries++; // Wait until all entries are processed before logging the result if (processedEntries === entries.length) { console.log(`Total files: ${fileCount}`); } }); }); });
Key Notes:
- We use
path.join()to create full paths for each entry—readdironly returns names, not full paths, so we need this to check file status correctly. fs.lstat()checks the entry itself (great for avoiding symlink confusion); swap it withfs.stat()if you want to count symlinks that point to files.- The
processedEntriescounter ensures we only log the count once all async status checks are done.
Option 2: Async/Await (Cleaner, Modern)
If you prefer avoiding callback nesting, use the Promise-based file system API with async/await:
const fs = require('fs').promises; const path = require('path'); async function countFiles(dir) { try { const entries = await fs.readdir(dir); let fileCount = 0; for (const entry of entries) { const fullPath = path.join(dir, entry); const stats = await fs.lstat(fullPath); if (stats.isFile()) fileCount++; } console.log(`Total files: ${fileCount}`); return fileCount; } catch (err) { console.error('Error:', err); } } countFiles(process.cwd());
Option 3: High-Performance (Node.js v18+)
For newer Node.js versions, use the withFileTypes option in readdir—this avoids extra system calls by returning entry type info directly:
const fs = require('fs').promises; async function countFiles(dir) { try { // Get entries with type metadata included const entries = await fs.readdir(dir, { withFileTypes: true }); // Filter only files and count them const fileCount = entries.filter(entry => entry.isFile()).length; console.log(`Total files: ${fileCount}`); return fileCount; } catch (err) { console.error('Error:', err); } } countFiles(process.cwd());
This is the most efficient method since it cuts down on the number of file system operations needed.
内容的提问来源于stack exchange,提问作者Ankit Parmar
相关产品推荐
相关产品推荐

