惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

WordPress大学
WordPress大学
大猫的无限游戏
大猫的无限游戏
B
Blog
阮一峰的网络日志
阮一峰的网络日志
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
博客园 - 【当耐特】
Jina AI
Jina AI
博客园 - 聂微东
T
The Blog of Author Tim Ferriss
宝玉的分享
宝玉的分享
L
LangChain Blog
M
MIT News - Artificial intelligence
Blog — PlanetScale
Blog — PlanetScale
腾讯CDC
酷 壳 – CoolShell
酷 壳 – CoolShell
Y
Y Combinator Blog
F
Fortinet All Blogs
H
Help Net Security
B
Blog RSS Feed
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Apple Machine Learning Research
Apple Machine Learning Research
S
SegmentFault 最新的问题

博客园 - hjswlqd

python pip 离线包安装 whl格式 tar gz格式 py-radius mysql 连接查询 左连接 右连接 笛卡尔积 等 python linux 调试 vscode timeline不显示|不正常|异常|no filtered timeline information was provided|Timeline does not work es scroll id 每次都相同 python 安装 echarts的渐变色配置 LinearGradient 联想 进入bios u盘启动 kibana筛选数据 vscode python 3.7 pylance debugpy 插件 vsix vsix 离线 编译 转 | 一次搞懂数据大屏适配方案 (vw vh、rem、scale) 分辨率 缩放比 转 | element-ui组件table去除下方滚动条,实现鼠标左右拖拽移动表格 vscode 提示js 函数的插件 | vue3项目的插件 Window中查看端口被哪个进程占用,并结束进程的方法 python windows命令行 批处理 统计算指定后缀,格式的文件 保存 |下载 | 提取 win10 win11 电脑 锁屏壁纸 vscode process terminal 3221225506 终端打不开 默认打开powershell
nodejs 统计算指定后缀,格式的文件
hjswlqd · 2024-06-23 · via 博客园 - hjswlqd

都是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)} 文件。`);
    }
});