从插入到字符串变量的html文件中替换字符串

时间:2018-09-15 19:46:33

标签: javascript node.js string

我有一个代码可以将字符串转换为从变量派生的新字符串

const htmlstring = fs.readFileSync(config.message.letter);


function replace_tags(input, email) {
    return input
    .replace("{randomip}", random.ip)
    .replace("{email}", email)
    .replace("{date}", random.date);
}


function get_customised_message_template(email) {
    return {
        subject: replace_tags(config.message.subject, email),
        fromname: replace_tags(config.message.fromname, email),
        fromemail: replace_tags(config.message.fromemail, email),
        html: replace_tags(htmlstring, email) // >> here the error
    };
}

在这里,我想使用readfilesync替换输入htmlstring变量的HTML文件中的字符串

HTML文件中的示例

<b>mati lu anjeng {email} {randomip}</b>

我需要使用replace_tags()函数像其他标签一样替换标签 但我收到此错误

(node:4784) UnhandledPromiseRejectionWarning: TypeError: input.replace is not a function

我应该怎么做才能胜过

2 个答案:

答案 0 :(得分:0)

这可能是因为.readFileSync返回了一个缓冲区而不是一个字符串,并且.replace方法是一个字符串方法。因此请尝试将读取缓冲区转换为utf8编码的字符串,如下所示

const htmlstring = fs.readFileSync(config.message.letter)
                     .toString('utf8');

答案 1 :(得分:0)

您收到此错误是因为fs.readFileSync()默认情况下会重新调整字节缓冲区,而replace是字符串类型的函数。您可能需要像@Abdulfatai答案中那样将缓冲区转换为字符串,或者在读取文件时指定编码,如下所示:

const htmlstring = fs.readFileSync(config.message.letter, 'utf-8');