Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

fs.readFile find a placehold and replace, Handlebars js also an option if need be

I currently load a file in node with fs.readFileSync:

const filename = ‘test.html’;
const html_code = fs.readFileSync(/var/www/vhosts/example.com/httpdocs/html/${filename}, ‘utf8’);

in test.html I have this div:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

<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>

Is there away I can search the html for the {{ Text }} string and replace it with something else?
I tried this:

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

This doesn’t work and I also tried:

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;
  });

Which also doesn’t work. How can I accomplish this with or with out an engine like handlebars?

>Solution :

fs.readFileSync() doesnt accept a third callback argument, it is synchronous and is returned directly to the html_code variable that you assigned to. (The one that accepts 3 arguments is fs.readFile() but it is asynchronous.)

In addition, String.prototype.replace() in JS only replace the first instance, try regex instead: /{{ Test }}/g, where g is flag for global replace. The function also doesn’t replace the string in-place but rather return a new string with the substring replaced. The code below should works fine:

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading