npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@dragon708/docmind-docx

v1.9.0

Published

DOCX text and HTML (Mammoth) plus semantic structure from OOXML (JSZip + @xmldom/xmldom) for DocMind.

Readme

@dragon708/docmind-docx

Extracción de texto plano, HTML y imágenes incrustadas desde .docx. El texto/HTML usa Mammoth; las imágenes se leen del ZIP interno (word/media/) con JSZip.

Contenido de esta guía

  1. Instalación
  2. Uso rápido
  3. Tipos exportados
  4. Métodos y funciones (extractImagesFromDocx, extractTextFromDocx, convertDocxToHtml, analyzeDocx, …)
  5. Opciones DocxToHtmlOptions (Mammoth)
  6. Seguridad
  7. Licencia

Instalación

npm install @dragon708/docmind-docx

Dependencias runtime: mammoth, jszip.

Uso rápido

import { readFile } from "node:fs/promises";
import { analyzeDocx, extractTextFromDocx, convertDocxToHtml } from "@dragon708/docmind-docx";

const buffer = await readFile("documento.docx");

const full = await analyzeDocx(buffer);
// full.text, full.html, full.warnings, full.kind === "docx"

const soloTexto = await extractTextFromDocx(buffer);
const soloHtml = await convertDocxToHtml(buffer);

Tipos exportados

| Tipo | Descripción | |------|-------------| | DocxBinaryInput | Entrada binaria: Buffer | Uint8Array | ArrayBuffer. | | DocxToHtmlOptions | Opciones opcionales de Mammoth para la conversión a HTML (ver tabla más abajo). | | ExtractTextResult | { text: string; warnings: string[]; pages?: string[] } (ver splitByRenderedPages). | | ExtractTextOptions | { splitByRenderedPages?: boolean } para texto paginado. | | ConvertHtmlResult | { html: string; warnings: string[] } | | DocxAnalysisResult | { kind: "docx"; text: string; html: string; warnings: string[] } | | DocxEmbeddedImage | Una imagen extraída: filename, zipPath, mediaType, data, base64. | | ExtractImagesFromDocxResult | { images: DocxEmbeddedImage[]; warnings: string[] } |

Métodos y funciones

extractImagesFromDocx(input)

  • Parámetros: input: DocxBinaryInput
  • Retorno: Promise<ExtractImagesFromDocxResult>
  • Qué hace: Lista los ficheros bajo word/media/ del DOCX (ZIP) y devuelve cada uno con bytes, Base64 (sin prefijo data:) y mediaType inferido por extensión. Si no hay imágenes, images es []. Si el archivo no es un ZIP válido, images es [] y warnings lo indica (no lanza).

Helper docxImageToDataUri(image) devuelve data:<mime>;base64,<payload> para usar en navegador como href de descarga o <img src>.

Ejemplo (Node: guardar en disco):

import { writeFile } from "node:fs/promises";
import { extractImagesFromDocx } from "@dragon708/docmind-docx";

const { images, warnings } = await extractImagesFromDocx(buffer);
for (const img of images) {
  await writeFile(img.filename, Buffer.from(img.data));
}

Ejemplo (navegador: enlace de descarga):

import { docxImageToDataUri, extractImagesFromDocx } from "@dragon708/docmind-docx";

const { images } = await extractImagesFromDocx(arrayBuffer);
const img = images[0];
if (img) {
  const a = document.createElement("a");
  a.href = docxImageToDataUri(img);
  a.download = img.filename;
  a.click();
}

Nota: incluye todos los ficheros directamente bajo word/media/ (no subcarpetas). El MIME se infiere por extensión; si no coincide con tipos habituales, se usa application/octet-stream. No comprueba si el XML del documento referencia cada fichero.


extractTextFromDocx(input, options?)

  • Parámetros: input: DocxBinaryInput, options?: ExtractTextOptions
  • Retorno: Promise<ExtractTextResult>
  • Qué hace: Obtiene texto sin marcas HTML. La estructura es aproximada (no conserva maquetación fina).
  • splitByRenderedPages: true (por defecto es false): antes de Mammoth se inyectan marcas en word/document.xml donde Word suele guardar saltos de página (lastRenderedPageBreak, saltos explícitos, pageBreakBefore). El resultado en text queda como:
    Page 1 --------
    …contenido página 1…
    
    Page 2 --------
    …contenido página 2…
    Además se rellena pages con un array (solo cuerpos, sin la línea Page N). Si no se encuentra ninguna pista de salto, se devuelve una sola página y un warning descriptivo.
  • Helpers exportados (avanzado): injectDocxPageBreakMarkers, DOCX_RAW_PAGE_BREAK_MARKER, formatDocxRawTextByPages.

Si el buffer no es un DOCX válido, Mammoth suele lanzar error (no devuelve objeto vacío).


convertDocxToHtml(input, htmlOptions?)

  • Parámetros: input: DocxBinaryInput, htmlOptions?: DocxToHtmlOptions
  • Retorno: Promise<ConvertHtmlResult>
  • Qué hace: Genera un fragmento HTML (no documento completo con <html>). Imágenes incrustadas: por defecto DocMind usa data-URI en src salvo que definas otro convertImage.

analyzeDocx(input, htmlOptions?)

  • Parámetros: input: DocxBinaryInput, htmlOptions?: DocxToHtmlOptions
  • Retorno: Promise<DocxAnalysisResult>
  • Qué hace: Ejecuta en paralelo extracción de texto y conversión a HTML; une los warnings de ambas pasadas. Si algo falla de forma excepcional, no lanza: devuelve text y html vacíos y un warnings con mensaje error: Failed to read DOCX: ….

docxImagesAsDataUri()

  • Parámetros: ninguno
  • Retorno: Valor apto para la opción Mammoth convertImage.
  • Qué hace: Construye <img src="data:…;base64,…"> para imágenes inline. Es el predeterminado de este paquete cuando no pasas convertImage en htmlOptions. Puedes usarla explícitamente o sustituirla por mammoth.images.dataUri u otra estrategia (p. ej. escribir archivos en disco).

Ejemplo explícito:

import mammoth from "mammoth";
import { convertDocxToHtml, docxImagesAsDataUri } from "@dragon708/docmind-docx";

await convertDocxToHtml(buffer, {
  convertImage: docxImagesAsDataUri(),
});

// O la helper de Mammoth (muy similar):
await convertDocxToHtml(buffer, {
  convertImage: mammoth.images.dataUri,
});

Opciones DocxToHtmlOptions (Mammoth)

Se reenvían a mammoth.convertToHtml. Campos habituales:

| Opción | Descripción breve | |--------|---------------------| | styleMap | Reglas personalizadas de mapeo de estilos (string multilínea o array de líneas). | | includeEmbeddedStyleMap | Usar el mapa incrustado en el .docx. | | includeDefaultStyleMap | Usar el mapa por defecto de Mammoth. | | convertImage | Cómo convertir cada imagen (por defecto en DocMind: data-URI vía docxImagesAsDataUri). | | ignoreEmptyParagraphs | Omitir párrafos vacíos en el HTML. | | idPrefix | Prefijo para ids generados (notas, etc.). | | externalFileAccess | Permitir lectura de recursos externos referenciados (riesgo con documentos no confiables). | | transformDocument | Transformación del árbol del documento antes del HTML (avanzado). |

Detalle y sintaxis de styleMap: documentación de Mammoth.

Seguridad

Mammoth no sanea el contenido del documento. No uses conversión a HTML con entrada no confiable sin un paso posterior de sanitización (p. ej. para XSS) si vas a insertar el HTML en una página.

Licencia

MIT (alineada con el monorepo DocMind).