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

Next.js应用添加sitemap.xml时出现ENOENT目录不存在错误求助

解决Next.js站点地图生成时的ENOENT目录不存在错误

错误原因

Error: ENOENT: no such file or directory, scandir 'pages' 是因为代码中使用相对路径 "pages" 读取目录,但Next.js服务器端运行环境的当前工作目录不一定是项目根目录,导致无法定位到pages文件夹。

修复方案

改用绝对路径访问pages目录,通过process.cwd()获取项目根目录,结合path模块拼接正确路径,同时优化路径生成逻辑以适配多文件后缀和index页面场景。

修改后的完整代码

import * as fs from "fs"
import * as path from "path"
import { getDocuments } from "../firebase/firestore"

const Sitemap = () => {
  return null
}

export const getServerSideProps = async ({ res }) => {
  const BASE_URL = "https://www.example.com"

  // 用绝对路径定位pages目录
  const pagesDir = path.join(process.cwd(), "pages")
  const staticPaths = fs
    .readdirSync(pagesDir)
    .filter((staticPage) => {
      // 排除无需生成站点地图的页面和目录
      return !["sitemap.xml.js", "404.js", "_app.js", "_document.js", "api"].includes(
        staticPage
      )
    })
    .map((staticPagePath) => {
      // 跳过api目录(防止遗漏过滤)
      if (staticPagePath === "api") return null
      // 移除所有文件后缀(兼容js/ts/jsx/tsx)
      const pathWithoutExt = staticPagePath.replace(/\.(js|ts|jsx|tsx)$/, "")
      // index页面对应网站根路径,而非/index
      return pathWithoutExt === "index" ? BASE_URL : `${BASE_URL}/${pathWithoutExt}`
    })
    .filter(Boolean) // 过滤掉无效的null值

  const collectionOne = await getDocuments("collection-one")
  const collectionTwo = await getDocuments("collection-two")

  const collectionOnePaths = collectionOne.map((singleDocument) => {
    return `${BASE_URL}/collection-one/${singleDocument.id}`
  })
  const collectionTwoPaths = collectionTwo.map((singleSolutions) => {
    return `${BASE_URL}/collection-two/${singleSolutions.id}`
  })

  const allPaths = [...staticPaths, ...collectionOnePaths, ...collectionTwoPaths]

  const sitemap = `<?xml version="1.0" encoding="UTF-8"?>
    <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
      ${allPaths
        .map((url) => {
          return `
            <url>
              <loc>${url}</loc>
            </url>
          `
        })
        .join("")}
    </urlset>
  `

  res.setHeader("Content-Type", "text/xml")
  res.write(sitemap)
  res.end()

  return {
    props: {},
  }
}

export default Sitemap

额外注意事项

  • 确认项目根目录下确实存在pages文件夹,且拼写正确(区分大小写)。
  • 若使用Next.js 13+的App Router而非Pages Router,此方法不适用,建议使用官方推荐的sitemap库或App Router专用生成方式。
  • 修改后的代码会自动将index页面映射为网站根路径,同时兼容多种页面文件后缀。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:05:10