1

我有一个输出页面负载分析测试结果的 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 的初学者,非常感谢任何提示。

4

1 回答 1

1

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

要读取测试结果的 JSON 文件并从中制作 HTML 页面,我必须为此 Node 模块 (ran npm init) 创建一个 package.json 文件。创建文件后,我在 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 模板(像这样)。

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

于 2017-07-31T22:04:54.393 回答