Is there any approach to count the charactor or word number in all docs? #4786
Unanswered
CloudeaSoft
asked this question in
Q&A
Replies: 1 comment
-
|
There's no built-in feature for this, but you can write a simple script that runs during build. Here's a practical approach: Create a import { readdir, readFile, writeFile } from "fs/promises";
import { join, extname } from "path";
async function getFiles(dir) {
const entries = await readdir(dir, { withFileTypes: true });
const files = [];
for (const entry of entries) {
const full = join(dir, entry.name);
if (entry.isDirectory() && !entry.name.startsWith(".")) {
files.push(...(await getFiles(full)));
} else if ([".md", ".mdx"].includes(extname(entry.name))) {
files.push(full);
}
}
return files;
}
async function countWords() {
const docsDir = "./content"; // adjust to your docs path
const files = await getFiles(docsDir);
let totalWords = 0;
let totalChars = 0;
const perFile = [];
for (const file of files) {
const text = await readFile(file, "utf-8");
// Strip frontmatter
const content = text.replace(/^---[\s\S]*?---/, "");
// Strip MDX/JSX components and imports
const clean = content
.replace(/^import .+$/gm, "")
.replace(/<[^>]+>/g, "")
.replace(/```[\s\S]*?```/g, "")
.trim();
const words = clean.split(/\s+/).filter(Boolean).length;
const chars = clean.replace(/\s/g, "").length;
totalWords += words;
totalChars += chars;
perFile.push({ file, words, chars });
}
const result = { totalWords, totalChars, totalFiles: files.length, perFile };
await writeFile(".word-count.json", JSON.stringify(result, null, 2));
console.log(`Total: ${totalWords} words, ${totalChars} characters across ${files.length} files`);
}
countWords();Add it to your build step in {
"scripts": {
"count": "node scripts/word-count.mjs",
"prebuild": "node scripts/word-count.mjs",
"build": "next build"
}
}This runs before each build, saves results to |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
-
It's better to count it during building and save it in a temp file to improve performance.
Beta Was this translation helpful? Give feedback.
All reactions