Skip to main content

Improved: Count Docs Posts in Docusaurus Including Folders

· 3 min read
Serhii Hrekov
software engineer, creator, artist, programmer, projects founder

🔄 Update to: Count Number of Blog Posts in Docusaurus and Vercel

In my previous post, I shared a method to count the number of docs posts in a Docusaurus project and display it on your homepage, fully compatible with Vercel and static builds.

That method works great-if all your docs posts are plain .md or .mdx files in the docs/ directory.

But if you're like me and prefer organizing docs posts in folders (e.g., docs/folder/index.md), the previous approach silently misses those.

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

const blogDir = path.join(__dirname, '..', 'blog');
const docsDir = path.join(__dirname, '..', 'docs');

function countBlogEntries(dir) {
if (!fs.existsSync(dir)) return 0;

let count = 0;

const entries = fs.readdirSync(dir, { withFileTypes: true });

for (const entry of entries) {
const fullPath = path.join(dir, entry.name);

if (entry.isFile() && (entry.name.endsWith('.md') || entry.name.endsWith('.mdx'))) {
// Count individual markdown/mdx files
count += 1;
} else if (entry.isDirectory()) {
const innerFiles = fs.readdirSync(fullPath);
const hasMarkdown = innerFiles.some(f => f.endsWith('.md') || f.endsWith('.mdx'));
if (hasMarkdown) {
// Count the directory as one blog post
count += 1;
}
}
}

return count;
}

function countMarkdownFilesRecursive(dir) {
if (!fs.existsSync(dir)) return 0;

let count = 0;

const entries = fs.readdirSync(dir, { withFileTypes: true });

for (const entry of entries) {
const fullPath = path.join(dir, entry.name);

if (entry.isFile() && (entry.name.endsWith('.md') || entry.name.endsWith('.mdx'))) {
count += 1;
} else if (entry.isDirectory()) {
count += countMarkdownFilesRecursive(fullPath); // Recurse into subdirectories
}
}

return count;
}


const count_blog = countBlogEntries(blogDir);
const count_docs = countMarkdownFilesRecursive(docsDir);

const count = count_blog + count_docs;

// Ensure output folder exists
const outputPath = path.join(__dirname, '..', 'src', 'data');
if (!fs.existsSync(outputPath)) {
fs.mkdirSync(outputPath, { recursive: true });
}

// Write the blog count
fs.writeFileSync(
path.join(outputPath, 'blogStats.json'),
JSON.stringify({ count }, null, 2)
);

console.log(`✅ Blog post count (files + folders): ${count_blog}`);
console.log(`✅ Docs post count (files + folders): ${count_docs}`);
console.log(`✅ Total post count: ${count}`);