0

What's wrong here? Unable to get the output. "ReplaceHTML" doesn't return the required HTML code. In the replaceHTML function when I hit console.log before the 'return'(which I commented), then it gives the perfect answer but doesn't return anything after that. What's the reason? Any suggestion or help is most welcome.

const fs = require("fs");
const http = require("http");

const index = fs.readFileSync("index.html", "utf-8");
const dataIndex = fs.readFileSync("data.html", "utf-8");
const data = fs.readFileSync("json.json", "utf-8");
const objData = JSON.parse(data);

const replaceHTML = (temp, product) => {
  let output = temp.replace(/{%%NAME%%}/g, product.name);
  output = output.replace(/{%%USERNAME%%}/g, product.username);
  output = output.replace(/{%%EMAIL%%}/g, product.email);
  // console.log(output);
  return output;
};

const mainData = (temp, code) => {
  return temp.replace(/{%%MAINDATA%%}/g, code);
};

const server = http.createServer((req, res) => {
  const htmlData = objData
    .map((data) => {
      replaceHTML(dataIndex, data);
    })
    .join("");
  console.log(htmlData);

  let finalData = mainData(index, htmlData);
  res.end(finalData);
});

server.listen("3000", "127.0.0.1");
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
  </head>
  <body>
    {%%MAINDATA%%}
  </body>
</html>
<div>
  <h1>Name: {%%NAME%%}</h1>
  <h2>UserName: {%%USERNAME%%}</h2>
  <p>Email: {%%EMAIL%%}</p>
</div>

1 Answers1

1

You are not returning anything from the .map iterator:

const htmlData = objData.map((data) => {
   replaceHTML(dataIndex, data);
})

Just add the missing return:

const htmlData = objData.map((data) => {
   return replaceHTML(dataIndex, data);
})

Or remove the curly brackets:

const htmlData = objData.map((data) => replaceHTML(dataIndex, data))
moonwave99
  • 21,957
  • 3
  • 43
  • 64