Search code examples
javascriptjsonnode.jsmustachelighthouse

Rendering HTML from JSON with mustache


I have a Node.JS file that outputs page load analysis test results. I have stored the results in a file results.json, with JSON.stringify().

launchChromeAndRunLighthouse('https://www.microsoft.com/en-us/', flags, perfConfig).then(results => {
    fs.appendFile('results.json', JSON.stringify(results), (err) => {
        if(err){ throw err; }
        console.log('Data was appended to file!');
        var myObj = results.json; //problematic
        var JSON_to_HTML = mustache.render('This test was generated at this time: {{generatedTime}}.', myObj); //problematic
    });
});

Now I want to display the results in the browser, so I want to translate the JSON into HTML. I want to use mustache for this, but these lines aren't working for me:

var myObj = results.json;
var JSON_to_HTML = mustache.render('Test was generated at this time: {{generatedTime}}.', myObj);

I get the error "results isn't defined", the JSON file can't be read by mustache like this. I can't initialize "myObj" with the raw JSON, because it's about a million lines (and I need to later run tests for a whole bunch of pages, so I can't hardcode that right now).

I'm not sure how to translate this JSON file I have now into HTML. Does anyone have any ideas? I'm a beginner to Node and Mustache, any tips are highly appreciated.


Solution

  • A lot of googling led me to my own answer.

    To read the JSON file of the test results and make an HTML page out of it, I had to create a package.json file for this Node module (ran npm init). After I created the file, I opened it in sublime and edited the scripts so a CLI command 'build' would take the .json file, take a .mustache file with the stuff I wanted to display from the .json file, and stick those in a .html file.

    "scripts": { "build": "mustache results.json basicTemplate.mustache > theDisplay.html", "test": "echo \"Error: no test specified\" && exit 1" },

    results.json is where I stringified into, from the question. basicTemplate.mustache is for now

    {{generatedtime}} {{initialurl}}

    and theDisplay.html is just a basic html template (like this).

    Now when I run node <name of node module>, the results file is generated. Then I run npm run build, and this script I just created in the package.json is run. That modifies theDisplay.html. You should now be able to double-click theDisplay.html in Finder, and a browser opens up with the time the tests were generated, as well as the url of the page tested.