DocToc is a command-line tool and Node.js library that generates table of contents for markdown files inside local git repositories. It creates anchor-compatible links for multiple hosting platforms including GitHub, GitLab, Bitbucket, Ghost, and Node.js documentation sites.
npm install -g doctoc (CLI) or npm install doctoc (library)For programmatic usage:
const { transform } = require('doctoc');For ES modules:
import { transform } from 'doctoc';# Generate TOC for all markdown files in current directory
doctoc .
# Generate TOC for specific file
doctoc README.md
# Generate TOC with specific platform compatibility
doctoc --github README.md
doctoc --gitlab docs/
# Custom options
doctoc --maxlevel 3 --title "Contents" --all docs/const { transform } = require('doctoc');
const fs = require('fs');
// Read markdown content
const content = fs.readFileSync('README.md', 'utf8');
// Generate TOC
const result = transform(content, 'github.com', 4, 'Table of Contents');
if (result.transformed) {
// Write updated content
fs.writeFileSync('README.md', result.data, 'utf8');
console.log('TOC updated successfully');
} else {
console.log('No changes needed');
}DocToc is built around several key components:
Comprehensive CLI tool for processing markdown files with extensive configuration options and platform support.
doctoc [mode] [options] <path>Available Modes:
--github (default): GitHub-compatible anchors--gitlab: GitLab-compatible anchors--bitbucket: Bitbucket-compatible anchors--nodejs: Node.js documentation style--ghost: Ghost publishing platformOptions:
--help, -h: Show usage information--title, -t <title>: Custom TOC title--notitle, -T: Omit TOC title--maxlevel, -m <level>: Maximum heading level (1-6)--entryprefix <prefix>: Entry prefix character (default: -)--all: Include headers before TOC location--update-only, -u: Only update files that already have TOC--stdout, -s: Output to stdout instead of modifying filesTransform function for integrating TOC generation into Node.js applications and build processes.
function transform(
content,
mode,
maxHeaderLevel,
title,
notitle,
entryPrefix,
processAll,
updateOnly
);interface TransformResult {
transformed: boolean;
data?: string;
toc?: string;
wrappedToc?: string;
}Utilities for discovering and processing markdown files in directory structures.
function findMarkdownFiles(dir);