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

React中如何通过Fetch获取public目录指定文件夹下的所有JSON文件?

问题描述

项目结构:

- Root
    - node_modules
    - public
        - Parent
            - FolderA
                - FileA.json
                - FileB.json 
                - ...
                - FileN.json (1 <= n <= 100)
            - FolderB
            - ...
            - FolderN (1 <= n <= 30)
        - FolderIds.txt
    - src

已实现逻辑:通过fetch('/Parent/FolderIds.txt')加载文件,每行格式为FolderA-PriorityA-DisplayNameA-ListOrderA,已存入React状态。

需求:点击文件夹按钮时,获取对应文件夹下所有文件名数组,不能用fs模块(与create-react-app/webpack冲突),能否用fetch实现?

解决方案

直接用fetch请求文件夹路径(比如/Parent/FolderB)默认拿不到文件列表——因为静态文件服务器通常不会默认返回目录索引。可以用以下两种前端可行的方案:

方案1:预生成文件夹文件列表**(推荐)**

给每个Folder目录下新增一个filelist.txt,内容为该文件夹下所有文件名,每行一个:

FileA.json
FileB.json
...

点击按钮时,fetch对应文件夹的filelist.txt:

const getFolderFiles = async (folderName) => {
  try {
    const res = await fetch(`/Parent/${folderName}/filelist.txt`);
    const txt = await res.text();
    return txt.split('\n').filter(file => file.trim() !== ''); // 过滤空行
  } catch (err) {
    console.error('获取文件列表失败:', err);
    return [];
  }
};

// 调用示例(点击FolderB的按钮时)
getFolderFiles('FolderB').then(files => {
  // files即为FolderB下的文件名数组
  console.log(files);
});

可以写个本地运行的Node.js脚本批量生成这些filelist.txt,避免手动维护:

// generate-filelists.js(本地运行,无需打包到项目)
const fs = require('fs');
const path = require('path');

const parentDir = path.join(__dirname, 'public/Parent');

// 遍历Parent下的所有文件夹
fs.readdirSync(parentDir).forEach(folder => {
  const folderPath = path.join(parentDir, folder);
  if (fs.statSync(folderPath).isDirectory()) {
    // 获取文件夹下的所有json文件
    const files = fs.readdirSync(folderPath).filter(file => file.endsWith('.json'));
    // 写入filelist.txt
    fs.writeFileSync(path.join(folderPath, 'filelist.txt'), files.join('\n'));
  }
});

运行脚本:node generate-filelists.js,即可批量生成所有文件夹的文件列表。

方案2:用webpack的require.context静态扫描(仅适用于编译时已知的文件)

如果你的文件夹和文件都是编译前就存在的,可以用webpack的require.context静态获取所有文件路径,再提取文件名:

// 在React组件中使用
const getFolderFiles = (folderName) => {
  // 匹配Parent下对应文件夹的所有json文件
  const context = require.context('../public/Parent/', true, new RegExp(`^./${folderName}/.*\\.json$`));
  // 从模块路径中提取文件名
  return context.keys().map(key => key.split('/').pop());
};

// 调用示例
const folderBFiles = getFolderFiles('FolderB');
console.log(folderBFiles); // ["FileX.json", "FileY.json", ...]

注意:这种方式是编译时静态分析,如果后续在public文件夹中新增文件,需要重新编译项目才会生效。

补充说明

静态文件服务器(比如create-react-app内置的webpack-dev-server)默认不会返回目录的文件列表,除非专门配置开启目录索引,但create-react-app未开放该配置,所以前端无法直接通过fetch获取目录内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 04:45:16