You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Next.js中出现ESIDIR错误——遵循官方教程编写代码仍报错

解决Next.js中getStaticProps环节的EISDIR错误

我一眼就看出问题所在啦!这个EISDIR(Error, Is Directory)错误的核心原因是:你的posts目录里存在子目录,但代码默认把fs.readdirSync(postsDirectory)返回的所有条目都当成Markdown文件去读取,当尝试读取目录而非文件时,就会触发这个错误。

问题出在哪?

fs.readdirSync()会返回目标目录下的所有内容——包括文件、子文件夹、符号链接等,但你的代码直接遍历所有返回值,用fs.readFileSync()去读取它们。而fs.readFileSync()只能读取文件内容,传入目录路径时就会抛出EISDIR错误。

修复方案:过滤目录,只处理Markdown文件

修改lib/post.js里的getSortedPostsData函数,在处理前先过滤掉目录,只保留.md后缀的文件:

import fs from 'fs'
import path from 'path'
import matter from 'gray-matter'

const postsDirectory = path.join(process.cwd(), 'posts')

export function getSortedPostsData() {
  // Get file names under /posts
  const fileNames = fs.readdirSync(postsDirectory)
  
  // 新增:过滤掉目录,只保留.md格式的文件
  const postFileNames = fileNames.filter(fileName => {
    const fullPath = path.join(postsDirectory, fileName)
    const fileStats = fs.statSync(fullPath)
    // 确保是文件,且后缀为.md
    return fileStats.isFile() && fileName.endsWith('.md')
  })

  const allPostsData = postFileNames.map(fileName => {
    // Remove ".md" from file name to get id
    const id = fileName.replace(/\.md$/, '')
    // Read markdown file as string
    const fullPath = path.join(postsDirectory, fileName)
    const fileContents = fs.readFileSync(fullPath, 'utf8')
    // Use gray-matter to parse the post metadata section
    const matterResult = matter(fileContents)
    // Combine the data with the id
    return {
      id,
      ...matterResult.data
    }
  })
  // Sort posts by date
  return allPostsData.sort(({ date: a }, { date: b }) => {
    if (a < b) {
      return 1
    } else if (a > b) {
      return -1
    } else {
      return 0
    }
  })
}

额外建议

你可以检查一下posts目录,看看是不是不小心创建了子文件夹,或者放入了非.md格式的文件——这些都是触发错误的常见原因。加上过滤逻辑后,代码会更健壮,不会因为目录里的额外内容而崩溃。

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

火山引擎 最新活动