You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Node.js中如何正确定位sources文件夹以获取所有文件路径

问题原因及解决方案
  • 第一个ENOENT报错原因:你配置的app.use('/app', express.static(...))是Express的HTTP静态资源路由规则,仅作用于客户端发来的HTTP请求路径映射,Node.js内置的fs模块读取的是本地磁盘的真实文件路径,完全不识别这个路由前缀,直接传/app/sources会被fs识别为当前磁盘根目录下的app/sources文件夹,自然找不到对应文件。
  • 第二个返回undefined问题:你的ThroughDirectory函数没有显式返回值,所有的return都写在forEach的回调函数里,仅能终止当前回调执行,不会给外层函数返回结果,所以调用函数拿到的默认是undefined,你往全局Files数组push的内容是正常存储的,直接打印Files数组就能看到结果。

正确实现代码

const fs = require('fs')
const path = require('path')
// 1. 构造sources文件夹的真实本地绝对路径,__dirname为当前server.js文件所在的目录,自动适配不同系统的路径分隔符
const sourcesPath = path.join(__dirname, './views/app/files/sources')
const files = []
// 2. 改造遍历函数,支持返回结果数组
function throughDirectory(directory, fileList) {
  fs.readdirSync(directory).forEach(file => {
    const absolute = path.join(directory, file)
    if (fs.statSync(absolute).isDirectory()) {
      throughDirectory(absolute, fileList)
    } else {
      fileList.push(absolute)
    }
  })
  return fileList
}
// 调用并打印结果
const result = throughDirectory(sourcesPath, files)
console.log(result)

可选扩展:转换为可访问的HTTP路径

如果需要返回给前端的是可直接访问的静态资源路径,可以把拿到的本地绝对路径替换为对应的路由前缀:

const httpPath = absolute.replace(path.join(__dirname, './views/app/files'), '/app')

内容的提问来源于stack exchange,提问作者Sara Ree

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.05 14:15:03