Run it

Node Guide

A .docx built with fromMd goes through oconv.convert to .odt and to .pdf, the .odt is read back to Markdown with toMd to show what survived, and an unsupported pair (pdf → docx) shows the typed refusal. node kind.

Uses @awacloud/oconv (AGPL-3.0-only) over @awacloud/fw (Apache-2.0). This example's code is AGPL-3.0-only.

When to use it

A batch job or a build step that turns incoming Word files into OpenDocument or PDF without a Markdown detour and without an office suite on the machine: an intake pipeline, a publication step, a conversion service running under Bun or Node.

Copy-paste steps

  1. npm install @awacloud/oconv (it depends on @awacloud/fw, md, ooxml, odf, pdf and fonts).
  2. Copy main.js and run bun main.js out/ (or node main.js out/): it writes source.docx, converted.odt, converted.pdf and round-trip.md into out/ and prints one line per step.
  3. Replace fromMd by reading your own .docx bytes; convert({ bytes, name, target }) detects the source format from name's extension (or takes format) and never derives target.

What it shows

  • Wiring: one ModuleRuntime with @awacloud/oconv's fw_require and modules; rt.resolve('oconv').
  • convert: the four shipped pairs are docx>odt, odt>docx, docx>pdf, odt>pdf; the result carries bytes, the resolved format and target, lossy and the merged reader + writer losses. Any other pair throws oconv: unsupported pair — the script catches it and prints it as a report line, which the test pins.
  • Round trip: toMd on the converted .odt keeps the three headings, the bold run and the ordered list; convertedAt is explicit (a fixed value in the test) and lands in the front matter.
  • Stable output: report(result) prints sizes and loss codes only — no path, no timestamp — so a test can pin it; main() adds the output directory on its last line.
  • Not shown: the PDF options (opts.pdf) and the default-face pack (see the oconv-fonts example), images (assets), the Web Worker entry.

Code

main.js

javascriptAGPL-3.0-only68 lines

// SPDX-License-Identifier: AGPL-3.0-only
// Run: bun main.js <out-dir>   (or node main.js <out-dir>)
import { mkdirSync, writeFileSync } from 'node:fs';
import { join } from 'node:path';
import { fileURLToPath } from 'node:url';
import { ModuleRuntime } from '@awacloud/fw/core/runtime.js';
import { fw_require, modules } from '@awacloud/oconv';

const rt = new ModuleRuntime();
rt.registerAll([...fw_require, ...modules]);
const OCONV = rt.resolve('oconv');

export const SAMPLE = '# Field report\n\nMeasured on **site**, not assumed.\n\n'
    + '## Findings\n\n1. The pump runs hot\n2. The valve leaks\n\n## Next visit\n\nBring the gauge.\n';

/**
 * Document to document, no Markdown hop: a `.docx` (built here from Markdown so
 * nothing binary is checked in) becomes an `.odt` and a `.pdf` through
 * `oconv.convert`; the `.odt` is then read back to Markdown with `toMd` to show
 * what survived, and an unsupported pair is tried to show the typed refusal.
 * Writes `source.docx`, `converted.odt`, `converted.pdf` and `round-trip.md`.
 * @param {string} outDir
 * @param {{ markdown?: string, convertedAt?: string }} [opts] `convertedAt` goes into the round-trip front matter
 */
export async function run(outDir, { markdown = SAMPLE, convertedAt = new Date().toISOString() } = {}) {
    mkdirSync(outDir, { recursive: true });
    const docx = await OCONV.fromMd({ markdown, target: 'docx' });
    const odt = await OCONV.convert({ bytes: docx.bytes, name: 'source.docx', target: 'odt' });
    const pdf = await OCONV.convert({ bytes: docx.bytes, name: 'source.docx', target: 'pdf' });
    const back = await OCONV.toMd({ name: 'converted.odt', bytes: odt.bytes, convertedAt });
    const unsupported = await OCONV.convert({ bytes: pdf.bytes, name: 'converted.pdf', target: 'docx' })
        .then(() => null, (/** @type {Error} */ err) => err.message); // 'oconv: unsupported pair' — shown, not thrown
    const files = {
        'source.docx': docx.bytes, 'converted.odt': odt.bytes,
        'converted.pdf': pdf.bytes, 'round-trip.md': back.markdown,
    };
    for (const [name, content] of Object.entries(files)) writeFileSync(join(outDir, name), content);
    return { docx, odt, pdf, back, unsupported };
}

/**
 * Stable report lines: sizes, ledgers and the round trip, no path and no timestamp.
 * @param {Awaited<ReturnType<typeof run>>} result
 */
export function report({ docx, odt, pdf, back, unsupported }) {
    const ledger = (/** @type {{ code: string }[]} */ losses) => (losses.length
        ? losses.map((l) => l.code).join(', ')
        : 'no loss');
    return [
        `md → docx: ${docx.bytes.length} bytes (${ledger(docx.losses)})`,
        `docx → odt: ${odt.bytes.length} bytes (${ledger(odt.losses)})`,
        `docx → pdf: ${pdf.bytes.length} bytes (${ledger(pdf.losses)})`,
        `odt → md: ${back.anchors.length} headings kept (${ledger(back.losses)})`,
        `pdf → docx: ${unsupported ?? 'converted'}`,
    ];
}

/** @param {string[]} [argv] */
export async function main(argv = process.argv.slice(2)) {
    const outDir = argv[0];
    if (!outDir) return ['usage: bun main.js <out-dir>'];
    const result = await run(outDir);
    return [...report(result), `written to ${outDir}: source.docx, converted.odt, converted.pdf, round-trip.md`];
}

if (process.argv[1] && fileURLToPath(import.meta.url) === process.argv[1]) {
    for (const line of await main()) console.log(line);
}