nodejs 统计算指定后缀,格式的文件
都是gpt生成的
可用版本
const fs = require('fs');
const path = require('path');
function countHtmlFiles(dirPath) {
let count = 0;
const files = fs.readdirSync(dirPath);
files.forEach(file => {
const filePath = path.join(dirPath, file);
const stat = fs.statSync(filePath);
if (stat.isFile()) {
if (path.extname(filePath) === '.html') {
count++;
}
} else if (stat.isDirectory()) {
// 将递归调用得到的 count 值累加到当前 count 变量
count += countHtmlFiles(filePath);
}
});
return count;
}
// 测试
const targetDir = './myDirectory'; // 替换为您的目标目录
const htmlCount = countHtmlFiles(targetDir);
console.log(`目录 ${targetDir} 中包含 ${htmlCount} 个 HTML 文件。`);
不可用版本,
const fs = require('fs');
const path = require('path');
function countFilesByExtension(dirPath, extension) {
return new Promise((resolve, reject) => {
fs.readdir(dirPath, { withFileTypes: true }, (err, files) => {
if (err) {
reject(err);
} else {
let count = 0;
files.forEach(file => {
if (!file.isDirectory()) {
const filePath = path.join(dirPath, file.name);
if (path.extname(filePath) === extension) {
count++;
}
}
});
resolve(count);
}
});
});
}
// 示例:统计当前目录下所有.html文件的数量
const directory = '.'; // 当前目录,可以根据需要修改为其他目录路径
const extension = '.html';
countFilesByExtension(directory, extension)
.then(count => {
console.log(`在目录 '${directory}' 下,共有 ${count} 个 .${extension.slice(1)} 文件。`);
})
.catch(err => {
console.error('读取目录时出错:', err);
});
A: 上述nodejs版本,没有递归调用目录
Q: 您是对的,我之前的Node.js示例中确实没有递归处理子目录中的文件。为了修正这一点,我们可以修改Node.js的示例代码,使其能够递归地遍历目录及其所有子目录来统计指定文件类型的数量。下面是更新后的Node.js代码示例,实现了递归统计指定扩展名文件的功能:
仍不可用版本
const fs = require('fs');
const path = require('path');
function countFilesRecursively(dirPath, extension, callback) {
fs.readdir(dirPath, { withFileTypes: true }, (err, files) => {
if (err) {
return callback(err);
}
let count = 0;
files.forEach((file) => {
const filePath = path.join(dirPath, file.name);
if (file.isDirectory()) {
// 递归处理子目录
countFilesRecursively(filePath, extension, (recCount) => {
count += recCount;
if (--files.length === 0) {
callback(null, count);
}
});
} else if (path.extname(filePath) === extension) {
count++;
if (--files.length === 0) {
callback(null, count);
}
} else {
if (--files.length === 0) {
callback(null, count);
}
}
});
});
}
// 示例:统计当前目录及其子目录下所有.html文件的数量
const directory = '.';
const extension = '.html';
countFilesRecursively(directory, extension, (err, count) => {
if (err) {
console.error('读取目录时出错:', err);
} else {
console.log(`在目录 '${directory}' 及其子目录下,共有 ${count} 个 .${extension.slice(1)} 文件。`);
}
});

浙公网安备 33010602011771号