Skip to content
jshacks.dev
Node.js

Build a Static Site Generator With Node.js

Build a static site generator with Node.js using pure functions, front matter parsing, template literals, an index page and a watch mode.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the Node.js, JavaScript, npm and Vite logos.

A static site generator is a good program to write once, because it is nearly all pure functions. Files go in, strings come out, and each step can be tested by calling it. This post builds one on Node.js 26 with no dependencies: it reads Markdown-like pages with front matter, turns them into HTML with a small converter, wraps them in a template made of plain functions, writes an index page and rebuilds on change with node --watch. Along the way you will see why functions beat a template language for a project this size, and where that stops being true.

The pipeline as functions

The whole program is a chain of small steps. Each takes data and returns data.

Text
read files -> parse front matter -> render body -> apply layout -> write files

Keep the I/O at the two ends and the middle pure. A pure function has no side effects and returns the same output for the same input, so you can test the middle with plain assert calls and no temporary directories. Reading and writing stay in one small main function.

The project looks like this:

Text
site/
  build.js
  lib/
    frontmatter.js
    markdown.js
    layout.js
  content/
    index.md
    hello-world.md
    second-post.md
  dist/            (generated)

Front matter

A content file starts with a block of key: value lines between --- markers, then the body.

content/hello-world.mdText
---
title: Hello World
date: 2026-11-01
---
This is the **first** post. It has a [link](https://nodejs.org).

## A heading

A second paragraph.

The parser splits at the second marker and reads simple lines. It handles only flat string values, which is all this site needs. For nested data you would use YAML or JSON, but a parser you wrote in ten lines has no dependencies and no surprises.

lib/frontmatter.jsJavaScript
export function parseFrontMatter(source) {
  const match = source.match(/^---\n([\s\S]*?)\n---\n?([\s\S]*)$/);
  if (!match) return { data: {}, body: source };

  const data = {};
  for (const line of match[1].split("\n")) {
    const at = line.indexOf(":");
    if (at === -1) continue;
    data[line.slice(0, at).trim()] = line.slice(at + 1).trim();
  }
  return { data, body: match[2] };
}

const { data, body } = parseFrontMatter("---\ntitle: Hello\ndate: 2026-11-01\n---\nText here");
console.log(data, JSON.stringify(body));
Text
{ title: 'Hello', date: '2026-11-01' } "Text here"

Splitting on the first colon of each line, with indexOf, keeps a value such as title: Part 1: Setup intact, whereas a plain split(":") would break it into three pieces.

A small Markdown converter

A complete Markdown parser is a large project, and a good package exists, so for a real site you would use one. The converter below handles what the sample content needs: headings, paragraphs, bold, italic, inline code and links. It escapes HTML first, which is the step people forget.

lib/markdown.jsJavaScript
function escapeHtml(text) {
  return text
    .replaceAll("&", "&")
    .replaceAll("<", "&lt;")
    .replaceAll(">", "&gt;");
}

function inline(text) {
  return escapeHtml(text)
    .replace(/`([^`]+)`/g, "<code>$1</code>")
    .replace(/\*\*([^*]+)\*\*/g, "<strong>$1</strong>")
    .replace(/\*([^*]+)\*/g, "<em>$1</em>")
    .replace(/\[([^\]]+)\]\((https?:\/\/[^)\s]+)\)/g, '<a href="$2">$1</a>');
}

export function markdown(source) {
  return source
    .trim()
    .split(/\n{2,}/)
    .map((block) => {
      const heading = block.match(/^(#{1,3}) (.+)$/);
      if (heading) {
        const level = heading[1].length;
        return `<h${level}>${inline(heading[2])}</h${level}>`;
      }
      return `<p>${inline(block.replace(/\n/g, " "))}</p>`;
    })
    .join("\n");
}

console.log(markdown("## Title\n\nSome **bold** and `code` with [a link](https://nodejs.org)."));
Text
<h2>Title</h2>
<p>Some <strong>bold</strong> and <code>code</code> with <a href="https://nodejs.org">a link</a>.</p>

Escaping before the replacements means that a stray <script> in a content file becomes harmless text. The link pattern accepts only http: and https: addresses for the same reason a URL shortener does: a javascript: link should never become a clickable anchor. The honest limit is that this converter has no lists, code blocks or nested emphasis, and each of those is where hand-written converters go wrong. When you need them, replace this file with a library and keep the rest.

Layouts as functions

Template languages like Handlebars or Nunjucks exist to separate markup from logic. For a site with two layouts, a function that returns a template literal does the job, and you get the whole of JavaScript for loops and conditionals without learning a syntax.

lib/layout.jsJavaScript
function escapeAttr(text) {
  return String(text).replaceAll("&", "&amp;").replaceAll('"', "&quot;").replaceAll("<", "&lt;");
}

export function page({ title, body }) {
  return `<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>${escapeAttr(title)}</title>
</head>
<body>
<nav><a href="/">Home</a></nav>
<main>
${body}
</main>
</body>
</html>
`;
}

export function postPage(post) {
  return page({
    title: post.title,
    body: `<article>\n<h1>${escapeAttr(post.title)}</h1>\n<time>${post.date}</time>\n${post.html}\n</article>`,
  });
}

export function indexPage(posts) {
  const items = posts
    .map((p) => `<li><a href="/${p.slug}/">${escapeAttr(p.title)}</a> <time>${p.date}</time></li>`)
    .join("\n");
  return page({ title: "All posts", body: `<h1>All posts</h1>\n<ul>\n${items}\n</ul>` });
}

Notice that postPage and indexPage both reuse page. That is composition, and it gives you what template inheritance gives other systems with no extra concept. A new layout is a new function that calls page.

The build script

Now the impure shell. It reads every .md file in content, builds a list of posts, writes one index.html per post into its own folder, so URLs have no extension, and writes the index sorted by date.

build.jsJavaScript
import { readdir, readFile, writeFile, mkdir, rm } from "node:fs/promises";
import { basename } from "node:path";
import { parseFrontMatter } from "./lib/frontmatter.js";
import { markdown } from "./lib/markdown.js";
import { postPage, indexPage } from "./lib/layout.js";

const CONTENT = new URL("./content/", import.meta.url);
const DIST = new URL("./dist/", import.meta.url);

async function loadPosts() {
  const names = (await readdir(CONTENT)).filter((n) => n.endsWith(".md") && n !== "index.md");
  const posts = [];
  for (const name of names) {
    const { data, body } = parseFrontMatter(await readFile(new URL(name, CONTENT), "utf8"));
    posts.push({
      slug: basename(name, ".md"),
      title: data.title ?? basename(name, ".md"),
      date: data.date ?? "",
      html: markdown(body),
    });
  }
  return posts.sort((a, b) => b.date.localeCompare(a.date));
}

async function build() {
  const started = performance.now();
  const posts = await loadPosts();

  await rm(DIST, { recursive: true, force: true });
  await mkdir(DIST, { recursive: true });

  for (const post of posts) {
    const dir = new URL(`${post.slug}/`, DIST);
    await mkdir(dir, { recursive: true });
    await writeFile(new URL("index.html", dir), postPage(post));
  }
  await writeFile(new URL("index.html", DIST), indexPage(posts));

  const ms = Math.round(performance.now() - started);
  console.log(`built ${posts.length} posts in ${ms} ms`);
}

await build();

Sorting dates with localeCompare works because the dates are written as YYYY-MM-DD, an order where string comparison matches chronological order. Wiping dist first means a deleted source file also disappears from the output, which is the bug people meet when a generator only ever adds files.

Run it.

Shell
node build.js
find dist -type f | sort
Text
built 2 posts in 6 ms
dist/hello-world/index.html
dist/index.html
dist/second-post/index.html

The time will vary by machine, and for hundreds of posts it stays in the tens of milliseconds because everything is string work.

Watch mode and serving

Node.js has a built-in watcher, so rebuilding on save needs no tool. --watch-path limits what triggers a restart to the content and library folders, and since build.js runs once and exits, each change simply re-runs it.

Shell
node --watch-path=./content --watch-path=./lib --watch build.js

For a preview server, npx serve dist works, but the standard library can serve a folder too. A twelve-line static server using createReadStream and the folder-with-index.html rule is enough for local work, and you should not use it in production, where nginx or a CDN will do it better and with correct caching headers.

Testing a pure pipeline

Because the middle is pure, tests are direct calls.

site.test.jsJavaScript
import { test } from "node:test";
import assert from "node:assert/strict";
import { markdown } from "./lib/markdown.js";
import { parseFrontMatter } from "./lib/frontmatter.js";

test("escapes html in the body", () => {
  assert.equal(markdown("a <b> c"), "<p>a &lt;b&gt; c</p>");
});

test("keeps colons inside a front matter value", () => {
  const { data } = parseFrontMatter("---\ntitle: Part 1: Setup\n---\nx");
  assert.equal(data.title, "Part 1: Setup");
});
Text
✔ escapes html in the body (0.6ms)
✔ keeps colons inside a front matter value (0.3ms)
ℹ tests 2
ℹ pass 2
ℹ fail 0

What to add next

Real sites need more. An RSS feed is another function from posts to an XML string. Drafts are a front matter flag you filter in loadPosts. Incremental builds, which only rebuild changed files, matter once you have thousands of pages, and the usual approach is to cache by file modification time. Syntax highlighting for code blocks is the feature that most often pushes people to a Markdown library, since doing it well is a real project of its own. Asset handling, such as copying images and hashing file names for cache busting, is the other common addition.

Why pure functions pay off here

The generator is short, and the reason it stays easy to change is the boundary between pure and impure code. Every function in lib takes strings and returns strings. None of them reads a file, checks the clock or prints. That gives you three practical benefits.

Testing is trivial. To check that a heading is converted correctly you call markdown("## Title") and compare the result. There is no temporary directory, no mock and no setup. A test suite for the whole library runs in a few milliseconds, which means you actually run it on every save.

Reuse is trivial. The same markdown function that builds posts can render a comment, a README or the description in an RSS feed. Because it has no hidden inputs, it behaves the same in each place.

Change is local. If you decide to switch from a hand-written Markdown converter to a library, you replace one file and the rest of the pipeline neither knows nor cares. The same goes for swapping the layout for one that includes a sidebar. The impure build.js is the only code that knows where files live, so moving the content folder is a one-line edit.

There is a cost. Pure functions that return whole strings use more memory than a streaming approach, and for a site with a million pages that would matter. For a blog with a few thousand posts, the strings are small, the build finishes in a second and the simplicity is worth far more than the memory you save by streaming.

Be strict about one thing: do not let impurity creep into the library. The moment a layout function reads process.env or the current date, a build is no longer reproducible, and two runs of the same sources can produce different output. Pass the date or the base URL in as an argument instead.

Also inFunctions
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.