【问题标题】:How to get file structure array from fs in next.js如何从 next.js 中的 fs 获取文件结构数组
【发布时间】:2022-10-06 21:09:12
【问题描述】:

我想要的是

目前,我正在使用 Next 和 React 创建一个博客,并希望在前端显示文件的结构。 由于 StackOverflow 的回答,我已经使用 fs 为这个文件数组创建了变量。 通常,我在getStaticPaths 中使用getPosts 函数中的文件变量


export const getAllSubFolders = (
  baseFolder: string,
  folderList: string[] = [],
) => {
  const folders: string[] = fs
    .readdirSync(baseFolder)
    .filter((file) => fs.statSync(path.join(baseFolder, file)).isDirectory());

  folders.forEach((folder) => {
    folderList.push(path.join(baseFolder, folder));
    getAllSubFolders(path.join(baseFolder, folder), folderList);
  });
  return folderList;
};

export const getFilesInFolder = (rootPath: string) => fs
  .readdirSync(rootPath)
  .filter(
    (filePath) => !fs.statSync(path.join(rootPath, filePath)).isDirectory(),
  )
  .map((filePath) => path.normalize(path.join(rootPath, filePath)));

export const getFilesRecursively = (rootPath: string) => getAllSubFolders(rootPath)
  . reduce((result, folder) => [...result, ...getFilesInFolder(folder)], [] as string[]);


export const files = getFilesRecursively(\'pages\')

console.log(files)

  // [
  //   \'pages/posts/backend/aaa.mdx\',
  //   \'pages/posts/frontend/bbb.mdx\',
  //   \'pages/posts/retrospective/bbbccc.mdx\',
  //   \'pages/posts/retrospective/dddd.mdx\',
  // ]

问题是

当我在前端组件中调用 files 数组时,错误消息说, Module not found: Can\'t resolve \'fs\' 即使我在包含 getFilesRecursively 函数的文件中导入 fs。

如何在前端调用 files 数组?

    标签: node.js next.js filesystems


    【解决方案1】:

    我意识到在前端无法处理 fs,所以我使用 fs 制作了 JSON 文件。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-09-02
      • 1970-01-01
      • 1970-01-01
      • 2021-08-08
      • 1970-01-01
      • 1970-01-01
      • 2011-04-28
      • 2011-12-29
      相关资源
      最近更新 更多