替换文件循环中的多个值

Replace multiple values in file loop

本文关键字:文件 循环 替换      更新时间:2023-09-26

我正在尝试为自己构建一个快速而肮脏的静态站点生成器。

假设我有这个test.html文件:

{title}
{downloadpath}

这是我获得要替换的值的current.json

{
    "id": 123,
    "album" : [{
        "title": "Test EP",
        "albumid": 1234,
        "path": "test.zip"
     }]
}

我的替换函数如下所示:

    // Iterate through JSON object and replace
    function iterate(obj) {
        for (var property in obj) {
            if (obj.hasOwnProperty(property)) {
                if (typeof obj[property] == "object")
                    iterate(obj[property]);
                else
                console.log("replace {" + property + "} with " + obj[property] )
                htmldata.replace(/'{property'}/g, obj[property]);
            }
        }
    }
    iterate(json)
    var result = htmldata
    console.log(result)
    // Write new HTML
    fs.writeFile("test-" + json.id + ".html", result, 'utf8', function (err) {
        if (err) {
            return console.log(err);
        }
    });

如果我运行它,它的工作原理是这样的:

replace {id} with 123
replace {title} with Test EP
replace {albumid} with 1234
replace {path} with test.zip
{title}
{path}

你可以在那里看到问题。我认为它总是用输入文件替换编辑后的文件,所以我看不到任何变化。我想不通,如果有人能指出我正确的方向,我将不胜感激。

谢谢!

不使用大括号if语句会导致细微的错误!

你想要:

if (typeof obj[property] == "object") {
    iterate(obj[property]);
} else {
    console.log("replace {" + property + "} with " + obj[property] )
    htmldata.replace(/'{property'}/g, obj[property]);
}

否则,无论if上的条件如何,replace每次都会运行。

第二件事:您的正则表达式尝试匹配文字字符串"{property}"。相反,请尝试以下操作:

htmldata.replace(new RegExp("{" + property + "}", "g"), obj[property]);

第三件事:您没有将replace的结果分配htmldata。所以你需要这样做:

htmldata = htmldata.replace(new RegExp("{" + property + "}", "g"), obj[property]);