DEV Community

Tsumuri
Tsumuri

Posted on • Edited on

I want to convert an HTML file in express...

First of all, I want you to see there.

index.js quote

webdata = (fs.readFileSync(__dirname + '/web/wiki.html', 'utf8'));
webdata=String(webdata)
webdata = webdata.replace('{tmp.data.name}',articlesname);
 res.end(webdata);
Enter fullscreen mode Exit fullscreen mode

web/wiki.html

<!DOCTYPE HTML>
<html>
<head>
...
</head>
    <body>
      <h2>${tmp.data.name}</h2>
      <hr>
      <br>
      <div id="article">
          :
          :
    </body>
</html>
Enter fullscreen mode Exit fullscreen mode

Next, I will explain what I want to do.

I want to use replace to read the string "$ {tmp.data.name}" in HTML and use Node.js Express to make it the content of a variable.

However,

webdata=String(webdata)
webdata = webdata.replace('{tmp.data.name}',articlesname);
Enter fullscreen mode Exit fullscreen mode

does not work.
Variables are defined.
Also, I couldn't try it with a string instead of a variable.
Please help me...

Top comments (1)

Collapse
 
prajyu profile image
prajyu • Edited

Hey @tsumuri1017,
I strongly recommend to use a view engine and render page dynamically.

To use ejs as your view engine in express you need install the ejs package via npm

1: npm install ejs@3.1.6

2: Set your view engine in your server side
ie your index.js

// Add this line of code in your index.js 

app.set('view engine', 'ejs');
Enter fullscreen mode Exit fullscreen mode

3: Rename your wiki.html to wiki.ejs and rewrite wiki.ejs to

<!DOCTYPE HTML>
<html>
<head>
...
</head>
<body>
  <h2><%= articlesname %></h2> // webdata is a variable to render
  <hr>

  <br>
  <div id="article">
      :
      :
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

4: Render the ejs file on server side

articlesname = "Something"

/*

 Make changes with articlesname


*/
res.render('web/index',{articlesname}); // Change index to the path of the file
Enter fullscreen mode Exit fullscreen mode

And this should fix your issue.

For more on ejs and express read here

Hope this helps...