我有一个代码可以将字符串转换为从变量派生的新字符串
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
我应该怎么做才能胜过它
这可能是因为.readFileSync
返回缓冲区而不是字符串,并且.replace
方法是字符串方法。 因此,请尝试将读取缓冲区转换为utf8
编码字符串,如下所示
const htmlstring = fs.readFileSync(config.message.letter)
.toString('utf8');
您收到此错误是因为默认情况下fs.readFileSync()
重新调整字节缓冲区,并且replace
是字符串类型的函数。您需要将缓冲区隐藏为字符串@Abdulfatai如答案所示,或者在读取文件时指定编码,如下所示:
const htmlstring = fs.readFileSync(config.message.letter, 'utf-8');