How do I return a value from a simple jsdom function? How do I return a value from a simple jsdom function? express express

How do I return a value from a simple jsdom function?


I don't think you can do this using a return value, because done: is an async function.Try adding a callback to your tweakIt and get the new html by sending it as a parameter, e.g.

tweakIt(oldHtml, function(newHtml) {/*use the result here*/})


The new version of the JSDOM API no longer includes the 'done' callback option.

So I wrote a 'poor man's callback' to access a DOM variable only after it has been set.

function getSomeDOMVar(callback) {    const jsdom = require("jsdom");    const { JSDOM } = jsdom;    const dom = new JSDOM(`    <!DOCTYPE html>    <html>        <body>            <script>                var result; // globally scoped, undefined var, accessible in the node scope as dom.window.result                function doSomething() {                    // your code goes here                }                // then assign the data you want back to your the globally scoped var                result = doSomething();            </script>        </body>    </html>    `, {        runScripts: "dangerously",        resources: "usable"    });    // poor man's callback    function waitForVar() {        if (typeof dom.window.result !== 'undefined') {           cb(dom.window.result);        }    }    setTimeout(waitForVar, 1000);}getSomeDOMVar(function(result) {    console.log(result)});