New Research: Supply Chain Attack on Axios Pulls Malicious Dependency from npm.Details →
Socket
Book a DemoSign in
Socket

html-gen-docs

Package Overview
Dependencies
Maintainers
1
Versions
14
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

html-gen-docs

CLI para converter Markdown em HTML e publicar documentacao local

latest
Source
npmnpm
Version
1.8.0
Version published
Maintainers
1
Created
Source

html-gen-docs

CLI to convert Markdown files to HTML and serve the generated documentation on a local server.

Installation

Global (npm)

npm install -g html-gen-docs

After that, use html-gen from any directory on your machine.

Global (Bun)

bun add -g html-gen-docs

Without global installation

npx html-gen-docs --input docs --output docs-html

Quick usage

Convert and serve with explicit values:

html-gen --input docs/ --output docs-html/ --port 12334

Convert the current directory to a temp output with an auto-selected port:

html-gen

Clean the output directory before generating (removes stale files):

html-gen --input docs/ --output docs-html/ --clean

Show help:

html-gen --help

Show version:

html-gen --version

Available options

OptionShortDescriptionDefault
--input <dir>-iSource directory with .md filesCurrent directory
--output <dir>-oOutput directory for generated HTMLSystem temp dir
--port <port>-pPort for the local serverAuto-selected
--clean-cEmpty the output directory before generatingfalse
--help-hShow help
--version-vShow version

Default behavior:

  • --output not specified → Linux: /tmp/<timestamp>-<random>/ · Windows: C:\Temp\<timestamp>-<random>\
  • --port not specified → first available port is used automatically

Usage as a development dependency

If you want to pin the tool version within a project:

npm install --save-dev html-gen-docs

Add a script to your package.json:

{
  "scripts": {
    "docs:serve": "html-gen --input docs/ --output docs-html/ --port 12334"
  }
}

Run with:

npm run docs:serve

Supported features

  • Recursive conversion of .md to .html
  • Original folder structure preserved
  • YAML frontmatter with tolerant fallback for loose format
  • Mermaid (```mermaid block and ::: mermaid syntax)
  • MathJax 4 for mathematical formulas
  • Highlight.js for code
  • Express server with navigable listing of generated HTML files
  • File and folder metadata sourced from original .md files
  • node_modules automatically excluded from file counts
  • Automatic real-time updates with file watcher (.md only)
  • Terminal logs with friendly progress and access URL
  • --clean flag to remove stale output files before generation
  • All Files mode: single button to list every document across all folders, with a folder column to show the origin of each file
  • Search: find documents by filename or content; results show match badges and a content snippet; automatically activates All Files mode from the root index; when inside a folder, results are scoped to that folder and its subfolders

Navigation features

All Files mode

Click 📋 Todos os Arquivos in the listing toolbar to see every generated document from all folders in a single flat table. A Pasta (Folder) column shows the origin folder for each file. Click the button again to return to the normal folder view.

Type a term in the search bar and press Enter or click 🔎 Buscar.

  • Searches match against file names and file content (stored in memory from the original .md sources).
  • Results show a badge indicating whether the match was in the name, the content, or both, plus a short snippet of the matched text.
  • If you are on the root index, the search automatically switches to All Files mode so results span the entire documentation.
  • If you are inside a folder (e.g. /guias), results are scoped to that folder and its subfolders.
  • The watcher keeps the content index up to date: any .md file that is added, modified, or deleted is reflected in the next search without restarting the server.
  • Click ✖ Limpar to clear the search and return to the previous view.

Project structure

bin/
  html-gen.js                # global CLI entrypoint
src/
  app/run.js                 # main orchestration
  cli/parse-args.js          # argument parsing and validation
  config/
    runtime-config.js        # path resolution and defaults
    temp-output.js           # OS-specific temp directory
  conversion/
    discovery.js             # recursive markdown discovery
    converter.js             # markdown → html pipeline
  html/template.js           # final HTML page template
  markdown/
    frontmatter.js           # frontmatter parser with fallback
    renderer.js              # markdown-it + plugins
  server/
    directory-listing.js     # HTML listing of generated files
    start-server.js          # Express server initialization
test/
  *.test.js                  # automated tests (node:test)
docs/
  teste-completo.md          # full markdown document for render validation

Development

Install dependencies:

npm install

Run tests:

npm test

Run locally:

npm start -- --input docs --output docs-html --port 12334

With Bun:

bun ./bin/html-gen.js --input docs --output docs-html

CI/CD on GitLab

The project includes a pipeline in .gitlab-ci.yml with two stages:

  • test: runs npm test on branches and merge requests
  • release: runs npm run release on the main branch (semantic-release)

For automatic npm publishing, configure the following GitLab CI/CD variables:

  • NPM_TOKEN: npm automation token with publish permission
  • GL_TOKEN: GitLab personal access token (scope api)

FAQ

1. The command did not find any markdown files. What should I do?

Check that the directory specified with --input exists and contains .md files.

2. Do I always need to specify --output?

No. Without --output, the tool creates a temporary directory automatically.

3. Can I use it with both Node and Bun?

Yes. The package is implemented in CommonJS with libraries compatible with both runtimes.

4. The port is already in use. How to fix it?

Specify another port with --port, or omit it to use a free port automatically.

5. Does the tool watch for changes in real time?

Yes. After the initial publish, the watcher monitors .md file changes, reconverts them automatically, and prints the URL in the terminal.

6. The file counts seem wrong for a folder with scripts or dependencies. Why?

The tool only counts .md files and automatically excludes node_modules directories from all counts and size calculations.

7. How do I guarantee fresh data with no stale HTML?

Use --clean to empty the output directory before every run:

html-gen --input docs/ --output docs-html/ --clean

8. How does the search know about file content?

At startup, the tool reads all .md source files into an in-memory index. The file watcher keeps this index current: edits, new files, and deletions are reflected immediately without restarting the server.

9. How do I search only within a specific folder?

Navigate to the folder first (e.g. open http://localhost:PORT/?path=guias), then use the search bar. Results will be limited to that folder and its subfolders.

Additional documentation

  • Detailed API: docs/API.md
  • Contributing guide: CONTRIBUTING.md
  • Change history: CHANGELOG.md
  • Publishing to npm: docs/npm-publish-guide.md

License

ISC

html-gen-docs (Português)

CLI para converter arquivos Markdown em HTML e publicar a documentação gerada em um servidor local.

Instalação

Global (npm)

npm install -g html-gen-docs

Depois disso, use html-gen em qualquer pasta da máquina.

Global (Bun)

bun add -g html-gen-docs

Sem instalação global

npx html-gen-docs --input docs --output docs-html

Uso rápido

Converter e servir com valores explícitos:

html-gen --input docs/ --output docs-html/ --port 12334

Converter a pasta atual para saída temporária e porta automática:

html-gen

Limpar o diretório de saída antes de gerar (remove arquivos obsoletos):

html-gen --input docs/ --output docs-html/ --clean

Mostrar ajuda:

html-gen --help

Mostrar versão:

html-gen --version

Opções disponíveis

OpçãoCurtaDescriçãoPadrão
--input <pasta>-iPasta de origem com arquivos .mdPasta atual
--output <pasta>-oPasta de saída para os HTML geradosPasta temporária do sistema
--port <porta>-pPorta do servidor localAutomática
--clean-cEsvazia a pasta de saída antes de gerarfalse
--help-hExibe a ajuda
--version-vExibe a versão

Comportamento padrão:

  • Sem --output → Linux: /tmp/<timestamp>-<random>/ · Windows: C:\Temp\<timestamp>-<random>\
  • Sem --port → a primeira porta disponível é usada automaticamente

Uso como dependência de desenvolvimento

Se você quer versionar o uso da ferramenta dentro de um projeto:

npm install --save-dev html-gen-docs

No package.json, adicione um script:

{
  "scripts": {
    "docs:serve": "html-gen --input docs/ --output docs-html/ --port 12334"
  }
}

Execute com:

npm run docs:serve

Recursos suportados

  • Conversão recursiva de .md para .html
  • Preservação da estrutura de pastas
  • Frontmatter YAML com fallback tolerante para formato solto
  • Mermaid (bloco ```mermaid e sintaxe ::: mermaid)
  • MathJax 4 para fórmulas matemáticas
  • Highlight.js para código
  • Servidor Express com listagem navegável dos HTML gerados
  • Metadados de arquivos e pastas obtidos dos .md de origem
  • node_modules excluído automaticamente das contagens e tamanhos
  • Atualização automática em tempo real com watcher (somente .md)
  • Logs no terminal com progresso amigável e URL de acesso
  • Flag --clean para remover arquivos obsoletos antes da geração
  • Modo Todos os Arquivos: botão que lista todos os documentos de todas as pastas em uma única tabela, com coluna indicando a pasta de origem de cada arquivo
  • Busca: localiza documentos por nome ou conteúdo; exibe badges de correspondência e trecho do conteúdo encontrado; ativa automaticamente o modo Todos os Arquivos quando no índice raiz; quando dentro de uma pasta, limita os resultados àquela pasta e suas subpastas

Funcionalidades de navegação

Modo Todos os Arquivos

Clique em 📋 Todos os Arquivos na barra da listagem para ver todos os documentos gerados de todas as pastas em uma tabela plana. A coluna Pasta indica a pasta de origem de cada arquivo. Clique novamente no botão para voltar à navegação normal por pastas.

Busca

Digite um termo na barra de pesquisa e pressione Enter ou clique em 🔎 Buscar.

  • A busca funciona sobre nomes de arquivos e conteúdo (indexado em memória a partir dos .md de origem).
  • Os resultados exibem um badge indicando se a correspondência foi no nome, no conteúdo ou em ambos, além de um trecho do texto encontrado.
  • Se você estiver no índice raiz, a busca ativa automaticamente o modo Todos os Arquivos para cobrir toda a documentação.
  • Se você estiver dentro de uma pasta (ex.: /guias), os resultados ficam limitados àquela pasta e suas subpastas.
  • O watcher mantém o índice de conteúdo atualizado: arquivos .md adicionados, modificados ou excluídos são refletidos na próxima busca sem reiniciar o servidor.
  • Clique em ✖ Limpar para limpar a busca e retornar à visualização anterior.

Estrutura do projeto

bin/
  html-gen.js                # entrypoint CLI global
src/
  app/run.js                 # orquestração principal
  cli/parse-args.js          # parse e validação de argumentos
  config/
    runtime-config.js        # resolução de paths e defaults
    temp-output.js           # pasta temporária por SO
  conversion/
    discovery.js             # busca recursiva de markdown
    converter.js             # pipeline markdown -> html
  html/template.js           # template final da página html
  markdown/
    frontmatter.js           # parser de frontmatter com fallback
    renderer.js              # markdown-it + plugins
  server/
    directory-listing.js     # listagem html de arquivos gerados
    start-server.js          # inicialização do express
test/
  *.test.js                  # testes automatizados (node:test)
docs/
  teste-completo.md          # markdown completo para validar renderização

Desenvolvimento

Instalar dependências:

npm install

Executar testes:

npm test

Rodar localmente:

npm start -- --input docs --output docs-html --port 12334

Com Bun:

bun ./bin/html-gen.js --input docs --output docs-html

CI/CD no GitLab

O projeto inclui pipeline em .gitlab-ci.yml com dois estágios:

  • test: executa npm test em branches e merge requests
  • release: executa npm run release na branch main (semantic-release)

Para publicação automática no npm, configure no GitLab (CI/CD Variables):

  • NPM_TOKEN: token do npm com permissão de publish
  • GL_TOKEN: token de acesso ao GitLab (escopo api)

FAQ

1. O comando não encontrou arquivos markdown. O que fazer?

Verifique se a pasta informada em --input existe e contém arquivos .md.

2. Preciso informar sempre --output?

Não. Sem --output, a ferramenta cria uma pasta temporária automaticamente.

3. Posso usar em Node e Bun?

Sim. O pacote foi implementado em CommonJS com bibliotecas compatíveis com os dois runtimes.

4. A porta já está em uso. Como resolver?

Informe outra porta com --port, ou remova a opção para usar uma porta livre automaticamente.

5. A ferramenta observa alterações em tempo real?

Sim. Depois da publicação inicial, o watcher monitora mudanças em .md, reconverte automaticamente e exibe a URL novamente no terminal.

6. A contagem de arquivos parece errada numa pasta com scripts ou dependências. Por quê?

A ferramenta conta apenas arquivos .md e exclui automaticamente diretórios node_modules de todas as contagens e cálculos de tamanho.

7. Como garantir dados sempre frescos, sem HTML obsoleto?

Use --clean para esvaziar a pasta de saída antes de cada execução:

html-gen --input docs/ --output docs-html/ --clean

8. Como a busca conhece o conteúdo dos arquivos?

Ao iniciar, a ferramenta lê todos os arquivos .md de origem e cria um índice em memória. O watcher mantém esse índice atualizado: edições, novos arquivos e exclusões são refletidos imediatamente, sem reiniciar o servidor.

9. Como buscar apenas dentro de uma pasta específica?

Navegue até a pasta primeiro (ex.: abra http://localhost:PORTA/?path=guias) e use a barra de busca. Os resultados serão limitados àquela pasta e suas subpastas.

Documentação adicional

  • API detalhada: docs/API.md
  • Guia de contribuição: CONTRIBUTING.md
  • Histórico de mudanças: CHANGELOG.md
  • Publicação no npm: docs/npm-publish-guide.md

Licença

ISC

Keywords

markdown

FAQs

Package last updated on 30 Mar 2026

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts