Node.js:实现遍历文件夹下所有文件

Node.js:实现遍历文件夹

代码如下

js 复制代码
const fs = require('fs')
const path = require('path')

function traverseFolder(folderPath) {
  // 读取文件夹列表
  const files = fs.readdirSync(folderPath)

  // 遍历文件夹列表
  files.forEach(function (fileName) {
    // 拼接当前文件路径
    const filePath = path.join(folderPath, fileName)

    // 判断该路径是文件夹还是文件
    const stats = fs.statSync(filePath)

    if (stats.isDirectory()) {
      // 如果是文件夹,递归遍历
      traverseFolder(filePath)
    } else {
      // 如果是文件,执行操作
      console.log(filePath)
    }
  })
}

traverseFolder('./')

参考文章

如何使用Node.js遍历文件夹详解

相关推荐
codingWhat7 小时前
能效平台设计方案(打通gitlab和飞书)
后端·node.js·koa
见过夏天2 天前
Node.js 常用命令全攻略
node.js
前端双越老师2 天前
我从 0 开发的 AI Agent 智语项目发布了
前端·node.js·agent
kyriewen3 天前
2026 年了,还在用 Node.js?Bun 迁移实战:20 分钟搞定,附踩坑记录
前端·javascript·node.js
donecoding3 天前
3 条命令搞定闭环 Monorepo:Lerna 版本管理 + 拓扑构建 + 自定义分发
前端·前端框架·node.js
Flynt4 天前
npm v12 来了:allowScripts 默认关闭,我的项目差点跑不起来
安全·npm·node.js
叫我Paul就好5 天前
尝试 Node 搭建后端-开发框架
node.js
风止何安啊7 天前
网课倍速痛点解决:一套前端代码实现自由控速播放器
前端·javascript·node.js
糖拌西瓜皮7 天前
Node.js核心模块实战:文件、路径、HTTP与流处理
javascript·node.js
糖拌西瓜皮7 天前
Node.js工程化实践:包管理、TypeScript配置与代码质量
typescript·node.js