渲染 JSON 中的 HTML 留着小胡子

Rendering HTML from JSON with mustache

我有一个 Node.JS 文件输出页面负载分析测试结果。我已将结果存储在文件 results.json 中,其中 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
    });
});

现在我想在浏览器中显示结果,所以我想将JSON翻译成HTML。我想为此使用小胡子,但这些行对我不起作用:

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

我收到错误 "results isn't defined",JSON 文件不能像这样被 mustache 读取。我无法用原始 JSON 初始化 "myObj",因为它大约有一百万行(我需要稍后对一大堆页面进行 运行 测试,所以我不能硬编码现在)。

我不确定如何将我现在拥有的 JSON 文件翻译成 HTML。有人有什么想法吗?我是 Node 和 Mustache 的初学者,非常感谢任何提示。

大量谷歌搜索使我找到了自己的答案。

要读取测试结果的 JSON 文件并从中制作一个 HTML 页面,我必须为此节点模块创建一个 package.json 文件(运行 npm init)。创建文件后,我在 sublime 中打开它并编辑 scripts 因此 CLI 命令 'build' 将获取 .json 文件,获取包含我想要的内容的 .mustache 文件从 .json 文件中显示,并将它们粘贴到 .html 文件中。

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

results.json 是我从问题中字符串化的地方。 basicTemplate.mustache 目前是

{{generatedtime}} {{initialurl}}

和 theDisplay.html 只是一个基本的 html 模板(如 this)。

现在当我运行node <name of node module>时,结果文件就生成了。然后我运行npm run build,而我刚刚在package.json中创建的这个脚本是运行。这修改了 theDisplay.html。您现在应该能够在 Finder 中双击 theDisplay.html,然后会打开一个浏览器,其中包含生成测试的时间以及测试页面的 url。