Registry / serialization / docx4js

docx4js

JSON →
library3.3.0jsnpmunverified

docx4js is a JavaScript library designed for parsing and manipulating Microsoft Word (.docx) and PowerPoint (.pptx) files. The current stable version is 3.3.0, though the project's major releases have a less frequent cadence, with the latest stable version published two years ago. It supports both Node.js and browser environments. A key differentiator is its performance-oriented parsing strategy: it traverses document content and identifies OpenXML models using a visitor pattern, rather than building and retaining a full in-memory parsed structure. This approach aims for lower memory consumption, making it suitable for environments where memory is a concern. Users can define custom handlers to extract specific content, styles, or attributes from the document, allowing for flexible data extraction tailored to application needs. While initially focused on DOCX, it gained PPTX support in version 3.1.30. It primarily serves use cases requiring content extraction, transformation, or minor modification of Office OpenXML documents.

npm install docx4js
INSTALL
IMPORT
SIG · DOCX4JS
D
docx4js
serializationjavascriptv3.3.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

docx4js
import docx4js from 'docx4js';
const docx4js = require('docx4js');
The library primarily uses a default export for its main API, optimized for ESM. While a `require` call for the main entry point might work in some CJS setups, direct named imports are preferred in newer Node.js versions.
ModelHandler
import ModelHandler from 'docx4js/lib/openxml/docx/model-handler';
import { ModelHandler } from 'docx4js/lib/openxml/docx/model-handler';
Specific internal modules often export a default class or function. Using `require('...').default` is necessary for CJS when the module exports a default.
load
docx4js.load(fileOrBlob);
import { load } from 'docx4js';
`load` is a method directly on the default exported `docx4js` object, not a named export from the root.

This quickstart demonstrates loading a DOCX file from disk (Node.js), rendering its basic structure, and extracting plain text content using a custom model handler. It illustrates the core `load`, `render`, and `parse` APIs.

import docx4js from 'docx4js'; import { promises as fs } from 'fs'; import path from 'path'; async function processDocxFile(filePath) { try { // For Node.js, read the file buffer const fileBuffer = await fs.readFile(filePath); const docx = await docx4js.load(fileBuffer); console.log(`Successfully loaded DOCX file: ${filePath}`); // Example 1: Render the document to a simple JSON-like structure const renderedContent = docx.render(function createElement(type, props, children) { return { type, props, children }; }); console.log('Rendered Content (first 5 children):', JSON.stringify(renderedContent.children.slice(0, 5), null, 2)); // Example 2: Parse document using a custom event handler to extract text let extractedText = ''; class MyModelHandler { onp({ children }) { // on paragraph extractedText += (children || []).map(child => child.getText()).join(''); extractedText += '\n'; // Add newline for paragraphs } onr({ children }) { // on run extractedText += (children || []).map(child => child.getText()).join(''); } ontext({ content }) { extractedText += content; } // Catch-all for other models if needed on(type, handler) { // A simple way to register handlers dynamically or catch all if (type === '*') console.log(`Found model: ${type}`); } } const handler = new MyModelHandler(); docx.parse(handler); console.log('\nExtracted Text (first 500 chars):\n', extractedText.substring(0, 500)); // Example 3: Create a blank document and save (Node.js only) // const newDocx = await docx4js.create(); // const newFilePath = path.join(__dirname, 'new_document.docx'); // await newDocx.save(newFilePath); // console.log(`Created a new blank DOCX file: ${newFilePath}`); } catch (error) { console.error('Error processing DOCX file:', error); } } // To run this, you would need a sample.docx file in the same directory // For a real application, replace 'sample.docx' with your actual file path const sampleDocxPath = path.join(process.cwd(), 'sample.docx'); processDocxFile(sampleDocxPath);
Debug
Known issues
breakingMajor versions (v1, v2, v3) of docx4js are completely different from each other, indicating that upgrading between major versions will require significant code changes as the API is not backward compatible.
fix
Thoroughly review the release notes and migration guides for each major version jump. Expect a complete rewrite of integration code when upgrading between v1, v2, and v3.
affects: >=1.0.0
gotchadocx4js's parsing approach focuses on traversal without keeping a full, mutable in-memory parsed structure. This means direct manipulation of a DOM-like object is not the primary pattern; instead, users interact via visitor-like handlers.
fix
Design your application to utilize the visitor pattern (`docx.parse(handler)`) or a rendering function (`docx.render(createElement)`) to process content. Do not expect to modify a traditional document object model after initial parsing. Modifications typically involve creating a new document or using specific save features.
affects: >=3.0.0
gotchaThe library's original goal included DOCX, PPTX, and XLSX support, but it was limited to DOCX for a long time. PPTX support was added in version 3.1.30, but XLSX is not currently supported.
fix
Verify that your specific Office OpenXML file type (.docx or .pptx) is supported by your docx4js version. Do not assume support for Excel (.xlsx) files.
affects: >=3.0.0
gotchaWhen using docx4js in a browser environment, direct file system access (e.g., `fs` module) is not available. The `load` method expects a `Blob` or `ArrayBuffer` from user input (e.g., file input element).
fix
For browser usage, ensure that file content is provided as a `Blob` or `ArrayBuffer` obtained through client-side file APIs (e.g., `FileReader`). Avoid Node.js-specific `fs` imports.
affects: >=3.0.0
Errors
Common errors & fixes
Module not found: Error: Can't resolve 'fs' in './node_modules/docx4js/lib'
Attempting to use docx4js in a browser environment without correctly handling Node.js-specific module imports, particularly the `fs` module which is used for file system operations.
fix
Ensure your build process (Webpack, Rollup, etc.) correctly shims or excludes Node.js modules for browser builds. When `docx4js.load()` is called, pass a `Blob` or `ArrayBuffer` in the browser instead of a file path.
TypeError: Cannot convert undefined or null to object
This error often occurs when `docx4js.load()` receives an invalid or empty input, such as a corrupt, non-existent, or incorrectly formatted DOCX file, leading to an attempt to access properties of `undefined`.
fix
Validate the input file (ensure it exists, is a valid .docx/.pptx, and is not empty) before passing it to `docx4js.load()`. Check the file buffer or blob content for integrity.
ReferenceError: URL is not defined
This error can occur in some JavaScript environments (e.g., older Node.js versions or specific bundler configurations for the browser) where the global `URL` constructor is not available or polyfilled, which `docx4js` might use internally for resource handling.
fix
Ensure your runtime environment provides the `URL` global object. In Node.js, this usually means using a recent version. For browser environments, ensure your build setup includes necessary polyfills if targeting older browsers.
Upgrade
Version history
3.3.0latest on npm
Audit
Dependencies
jsziprequiredHandles the underlying ZIP archive structure of DOCX/PPTX files, essential for reading and writing document components.
xmldomrequiredProvides DOM parsing capabilities for the XML content within the DOCX/PPTX archives in Node.js environments.
Agent activity
11 hits · last 30 days
node
10
OpenAI (training)
1
Resources