【问题标题】:Rendering HTML from JSON with mustache从带有小胡子的 JSON 渲染 HTML
【发布时间】:2017-08-01 06:04:54
【问题描述】:

我有一个输出页面负载分析测试结果的 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。我想为此使用 mustache,但这些行对我不起作用:

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

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

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

【问题讨论】:

  • launchChromeAndRunLighthouse 必须返回未定义。您通过呈现一些静态数据console.log(mustache.render('{{foo}}', {foo: 'bar'})) 应记录 bar 来验证 mustache 是否正常工作。
  • 当我在新文件中尝试console.log(mustache.render('{{foo}}', {foo: 'bar'})) 时,我收到一条错误消息,指出未定义小胡子。我安装了它,最初是在全球范围内安装的,但后来只是在本地安装的。我还需要做什么才能使用小胡子吗?编辑:我可以打开 JSON 文件并查看测试结果,它不是未定义的......

标签: javascript json node.js mustache lighthouse


【解决方案1】:

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

要读取测试结果的 JSON 文件并从中制作 HTML 页面,我必须为此 Node 模块创建一个 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中创建的这个脚本就运行了。这会修改 Display.html。您现在应该能够在 Finder 中双击 theDisplay.html,然后会打开一个浏览器,其中包含生成测试的时间以及测试页面的 url。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多