ESIDIR Error in NextJs, even if the code come from the official page
I need to learn Next.js for an interview, so I started to follow the tutorial published in Next.js official web page.
It was all ok, until I arrived at this section about the implementation of getStaticProps.
I wrote this code as the tutorial says:
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)
const allPostsData = fileNames.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
}
})
}
So I changed index.js to look like this:
import Head from 'next/head'
import Layout, { siteTitle } from '../components/layout'
import utilStyles from '../styles/utils.module.css'
import { getSortedPostsData } from '../lib/post'
export async function getStaticProps() {
const allPostsData = getSortedPostsData()
return {
props: {
allPostsData
}
}
}
export default function Home({ allPostsData }) {
return (
<Layout home>
<Head>
<title>{siteTitle}</title>
</Head>
<section className={utilStyles.headingMd}>
<p>[Your Self Introduction]</p>
<p>
(This is a sample website - you’ll be building a site like this on{' '}
<a href="https://nextjs.org/learn">our Next.js tutorial</a>.)
</p>
</section>
<section className={`${utilStyles.headingMd} ${utilStyles.padding1px}`}>
<h2 className={utilStyles.headingLg}>Blog</h2>
<ul className={utilStyles.list}>
{allPostsData.map(({ id, date, title }) => (
<li className={utilStyles.listItem} key={id}>
{title}
<br />
{id}
<br />
{date}
</li>
))}
</ul>
</section>
</Layout>
)
}
However, when I run the code onscreen I see this error:
I know that ESIDIR means "Error, Is Directory" but I can't find a way to fix it and I don't understand why I have this error.
Solution 1:
The problem is you're trying to read content of a directory not a file, this what EISDIR stands for.
To fix it use fs.statSync method to check wether the path is file or not. It might look like this:
fs.statSync(path.join(postsDirectory, fileName)).isFile()
UPD. Also I'd suggest to check wether file has .md
extension or not. Currently you just replace it if it presented. So even if file have different extension it would be processed by your code. Use check like this:
path.extname(fileName) === '.md'