fs.readFile 找到一个占位符并替换,如果需要,Handlebars js 也是一个选项

问题描述 投票:0回答:1

我目前使用 fs.readFileSync 在节点中加载一个文件:

const 文件名 = 'test.html'; const html_code = fs.readFileSync(

/var/www/vhosts/example.com/httpdocs/html/${filename}
, 'utf8');

在 test.html 我有这个 div:

<div id="g-ai0-1" class="g-Text g-aiAbs g-aiPointText" style="top:59.6648%;margin-top:-14.2px;left:49.9587%;margin-left:-46px;width:92px;">
    <p class="g-pstyle0">{{ Text }}</p>
</div>

我可以在 html 中搜索

{{ Text }}
字符串并将其替换为其他内容吗? 我试过这个:

html_code.replace('{{ Text }}', 'new string');

这个不行,我也试过了:

const html_code = fs.readFile(`/var/www/vhosts/example.com/httpdocs/html/${filename}`, 'utf8', (err, data) => {
      if(err) {
          res.send(`this is the error: ${err}`);
          console.error(err)
          return
      }
      data.replace('{{ Text }}', 'new string');
      return data;
  });

这也行不通。使用或不使用车把之类的引擎,我如何才能做到这一点?

node.js handlebars.js node.js-fs
1个回答
1
投票

fs.readFileSync()
不接受第三个回调参数,它是同步的并直接返回给您分配给的
html_code
变量。 (接受 3 个参数的是
fs.readFile()
但它是异步的。)

另外,JS中的

String.prototype.replace()
只替换第一个实例,试试正则表达式:
/{{ Test }}/g
,其中
g
是全局替换的标志。该函数也不会就地替换字符串,而是返回一个替换了子字符串的新字符串。下面的代码应该可以正常工作:

try {
  const html_code = fs.readFileSync(
    `/var/www/vhosts/example.com/httpdocs/html/${filename}`,
    'utf8'
  );
  const replaced_html = html_code.replace(/{{ Text }}/g, 'new string');
  // Do something with your replaced HTML
} catch (err) {
  res.send(`this is the error: ${err}`);
  console.error(err);
  return;
}
© www.soinside.com 2019 - 2024. All rights reserved.