javascript - 使用 mustache 从 JSON 渲染 HTML

标签 javascript json node.js mustache lighthouse

我有一个输出页面负载分析测试结果的 Node.JS 文件。我已使用 JSON.stringify() 将结果存储在文件 results.json 中。

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。我想为此使用 mustache ,但这些行对我不起作用:

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

我收到错误“结果未定义”,像这样的 mustache 无法读取 JSON 文件。我无法使用原始 JSON 初始化“myObj”,因为它大约有一百万行(我需要稍后对一大堆页面运行测试,所以我现在不能硬编码)。

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

最佳答案

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

要读取测试结果的 JSON 文件并从中制作一个 HTML 页面,我必须为这个 Node 模块创建一个 package.json 文件(运行 npm init )。创建文件后,我在 sublime 中打开它并编辑了 scripts因此 CLI 命令“构建”将获取 .json 文件,获取一个包含我想从 .json 文件中显示的内容的 .mustache 文件,并将它们粘贴到 .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 中创建的脚本。那修改了Display.html。您现在应该能够在 Finder 中双击 Display.html,并且会打开一个浏览器,其中包含生成测试的时间以及测试页面的 url。

关于javascript - 使用 mustache 从 JSON 渲染 HTML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45339755/

相关文章:

android - 在 View 寻呼机中加载多个选项卡内容而无需再次获取

java - 如何在java中查询json对象?

node.js - 全局安装的node-dev导致错误 "command not found"

python - 如何保证服务器身份?

javascript - Angular $compile 很慢,如何避免

javascript - Google App 脚本触发器 ID 格式

javascript - 删除 javascript 字符串中的制表符空格或换行符

node.js - Jade 插值 #{ } 与缓冲 =' '

JavaScript 难题

javascript - Google map 无法在模态窗口中正确呈现