HTML to Markdown in Functions on Objects

I’m trying to convert HTML string to Markdown string in a FoO, but I’m getting stuck. I found that turndown library can be used for that, so I installed it together with @types/turndown to get TypeScript definitions for this lib. Then I run this simple code:

import { Function } from "@foundry/functions-api";

import TurndownService = require('turndown');

export class MyFunctions {
    
    @Function()
    public myFunction(html: string): string {
        const turndownService = new TurndownService();
        return turndownService.turndown(html);
    }

}

And I get an error:

o is not a constructor.
Error Parameters: {}
TypeError: o is not a constructor
    at u.myFunction (UserCode:1:1435)
    at ie.executeFunctionInternal (FunctionsIsolateRuntimePackage:2:933189)
    at Ie (FunctionsIsolateRuntimePackage:2:932217)
    at async ie.executeFunction (FunctionsIsolateRuntimePackage:2:932560)
    at async userFunction (FunctionsInitialization:8:43)

The code is more or less in line with the usage example on the libs github page. I adjusted it a bit to TypeScript, am I making a mistake there? The error itself is really vague.

The turndown library has a default export. Therefore to import it you’d want to do:

import * as Turndown from "turndown";

You’d then be able to construct it as follows:

const turndown = new Turndown.default();

(this differs from the Node.js usage seen on GitHub as we do not support CommonJS)

However, the turndown library also relies on the existence of a global document object. Functions are run in a base V8 environment (“pure” JavaScript), so browser and Node.js APIs are generally not available (with the exception of setTimeout). You’ll need to find another library that can convert HTML to markdown using “pure” JavaScript.

There is a similar, widely-used library called node-html-markdown which does not rely on browser APIs. This should work.

1 Like