错误:ENOENT:没有此文件或目录,扫描目录 ‘pages’

huangapple go评论72阅读模式
英文:

Error: ENOENT: no such file or directory, scandir 'pages'

问题

我正在尝试在我的Next.js应用中添加站点地图,但当我访问`http://localhost:3000/sitemap.xml`页面时,它抛出以下错误消息:

错误:ENOENT:没有这样的文件或目录,扫描'directory'页面

错误:ENOENT:没有此文件或目录,扫描目录 ‘pages’

pages/sitemap.xml.js文件代码:

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

const Sitemap = () => {
  return null
}

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

  const staticPaths = fs
    .readdirSync("pages")
    .filter((staticPage) => {
      return !["sitemap.xml.js", "404.js", "_app.js", "_document.js", "api"].includes(
        staticPage
      )
    })
    .map((staticPagePath) => {
      return `${BASE_URL}/${staticPagePath.replace(".js", "")}`
    })

  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

请有人帮我解决这个问题?


<details>
<summary>英文:</summary>

I&#39;m trying to add a sitemap in my nextjs app but when I visit the `http://localhost:3000/sitemap.xml` page it throws this error message:

Error: ENOENT: no such file or directory, scandir 'pages'


[![enter image description here][1]][1]


  [1]: https://i.stack.imgur.com/cxuvB.png

pages/sitemap.xml.js file code:

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

const Sitemap = () => {
return null
}

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

const staticPaths = fs
.readdirSync("pages")
.filter((staticPage) => {
return !["sitemap.xml.js", "404.js", "_app.js", "_document.js", "api"].includes(
staticPage
)
})
.map((staticPagePath) => {
return ${BASE_URL}/${staticPagePath.replace(&quot;.js&quot;, &quot;&quot;)}
})

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 = &lt;?xml version=&quot;1.0&quot; encoding=&quot;UTF-8&quot;?&gt;
&lt;urlset xmlns=&quot;http://www.sitemaps.org/schemas/sitemap/0.9&quot;&gt;
${allPaths
.map((url) =&gt; {
return

<url>
<loc>${url}</loc>
</url>

})
.join(&quot;&quot;)}
&lt;/urlset&gt;

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

return {
props: {},
}
}

export default Sitemap


Anyone, please help me with this issue?

</details>


# 答案1
**得分**: 1

当您运行`npm run dev`命令启动您的Next.js应用时,工作目录被设置为**您的应用程序的根目录**,该目录可能不包含*pages目录*。

您可以使用`process.cwd()`方法获取应用程序的当前工作目录,然后将pages目录追加到路径中。

例如,在`readdirSync`中将`&quot;page&quot;`设置为`pagesDir = path.join(process.cwd(), &quot;pages&quot;);`

```javascript
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) => {
    return `${BASE_URL}/${staticPagePath.replace(".js", "")}`
  })

如果不起作用,请尝试以下方法:

const path = require('path');
const fs = require('fs');

const files = fs.readdirSync(path.resolve(__dirname, 'pages'));
英文:

when you run the npm run dev command to start your Next.js app, the working directory is set to the root directory of your app, which may not contain the pages directory.

you can use the process.cwd() method to get the current working directory of your app, and then append the pages directory to the path

For example set &quot;page&quot; in readdirSync to pagesDir = path.join(process.cwd(), &quot;pages&quot;);

const pagesDir = path.join(process.cwd(), &quot;pages&quot;);

  const staticPaths = fs
    .readdirSync(pagesDir)
    .filter((staticPage) =&gt; {
      return ![&quot;sitemap.xml.js&quot;, &quot;404.js&quot;, &quot;_app.js&quot;, &quot;_document.js&quot;, &quot;api&quot;].includes(
        staticPage
      )
    })
    .map((staticPagePath) =&gt; {
      return `${BASE_URL}/${staticPagePath.replace(&quot;.js&quot;, &quot;&quot;)}`
    })

if it doesn't work try it with:

const path = require(&#39;path&#39;);
const fs = require(&#39;fs&#39;);

const files = fs.readdirSync(path.resolve(__dirname, &#39;pages&#39;));

huangapple
  • 本文由 发表于 2023年3月8日 17:16:06
  • 转载请务必保留本文链接:https://go.coder-hub.com/75671224.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定