0

I have two variables like this in my node project

header ="Hello Header";
result =  `<html>
    </head>
        <body>
            <div class='modal'>
                <div class='header'>
                    ${header}
                </div>
            </div>
        </body>
        </html>`;

I want to load this html part from an html file and pass the header value on to it. How we can achieve it ?

I know we can use fs.readFile

fs.readFile("index.html", 'utf8', function (err, data) {
    result = data;
});

But how can I pass the header variable into this ?

Sanooj T
  • 1,317
  • 1
  • 14
  • 25
  • 2
    Pass `header` where? What are you trying to accomplish? What is the desired result? What exactly should happen with the loaded HTML? `header` is already inserted into the `result` string; what else do you need to do with it? Please [edit] and clarify your question. – Sebastian Simon Dec 07 '21 at 08:38
  • Is this [yet another duplicate of this](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron)? – Quentin Dec 07 '21 at 08:45
  • create a placeholder string in the html file and once load the html file then replace the pace holder string with `header` variable value – Azad Dec 07 '21 at 08:51

1 Answers1

1

The easiest and fastest solution would be to:

  • make the replaceable header part in the HTML discoverable with a pattern like {{ header }}

  • read the file as you would normally

    fs.readFile("index.html", 'utf8', function (err, data) { // make something here });

OR

you could use promises for better readability and compact code

import {promises} from "fs"
(async () => {
  const html = await promises.readFile(file, "utf8");
})()
  • then when you have the HTML in a variable just do:

    data.replace("{{ header }}", header)