2

I need to change html in Node.js.

1 i have to read date from datecenter

2 i have to change or add html code in NODE

actualy i need to read date and write it into html file

there is javascript code i point where i have to change html

var mysql = require("mysql");
var connection = mysql.createConnection({
 host: 'localhost',
 user: 'testuser',
 password: 'a',
 database: 'test',
 port: 3306
});




connection.connect();

 var read = connection.query("SELECT `Name` FROM `fruids`",function(error, result){
  if(error) throw error;
  console.log(result);
 });

 //~~~~~here i have to change inner

 connection.end();

this is html below

<html>
<head>
    <title>Регистрация</title>
    <meta charset="utf-8" />
    <style>
    p{
      text-align: right;
      margin-right: 252px;
      margin-top: -8px;
    }
    </style>
</head>
<body>
    <h1>Введите данные</h1>
    <form action="/register" method="post">
        <label>Имя</label><br>
        <input type="text" name="userName" /><br><br>
        <label>Email</label><br>
        <input type="text" name="userAge" /><br><br>
        <label>Повідомлення</label><br>
        <textarea type="text" name="userMess" ></textarea><br><br>

        <input type="submit" value="OK" />
        <input type="reset" value="Стерти" />

    </form>
    <form>
      <h1 style="text-align: right;
                  margin-top: -284px;
                  margin-right: 170px;
      ">Повідомлення</h1>
    <p class="inner" id="mesager">xss</p>
    </form>
     </body>
</html>

can i do something like this

var date;
var node;
node.nodeValue = node.nodeValue.replace(/lol/, "<span>"+date+"</span>")
Chipnick
  • 43
  • 1
  • 1
  • 6
  • You should share more details of your code. change HTML by Node.js are far too fewer information. – Nico Schuck Feb 03 '20 at 17:45
  • There are lots of ways to do what you're asking. You can use a DOM parser to parse the HTML and then edit its content. You can just use a search and replace/regex and replace a value. Without knowing more about what you are trying it's hard to tell you how to proceed. – David S. Feb 03 '20 at 18:37
  • when i try with DOM it say document didn't founded – Chipnick Feb 03 '20 at 20:00

2 Answers2

2

For editing html in nodejs, you can use cheerio

If "lol" was an element it would be quite straightforward replacing it:

let $ = require('cheerio').load(inputHtml)
$('lol').replaceWith(`<span>${date}</span>`)

However in your question it seems like you need to replace text matching /lol/ regex with <span>[date]</span>.

The code below does this by iterating all text nodes:

const $ = require('cheerio').load(inputHtml);
const getTextNodes=(elem)=>elem.type==='text'?[]:
        elem.contents().toArray()
        .filter(el=>el!==undefined)//I don't know why some elements are undefined
        .reduce((acc, el)=>
            acc.concat(...el.type==='text'?[el]:getTextNodes($(el))), [] )
    
    
let replaceRegex = /lol/;
let date = new Date().toLocaleDateString('en-US');

getTextNodes($(`html`))
    .filter(node=>$.html(node).match(replaceRegex))
    .map(node=>$(node).replaceWith($.html(node).replace(replaceRegex, `<span>${date}</span>`))  );

console.log($.html());

So for the following input:

<html>
    <head></head>
    <body>
        <p>This is some lol text</p>
        Some other lol text
    </body>
</html>

you would get the following output:

<html><head></head><body>
        <p>This is some <span>3/18/2021</span> text</p>
        Some other <span>3/18/2021</span> text
    
</body></html>
Marinos An
  • 9,481
  • 6
  • 63
  • 96
  • I want to know if these changes are permanent, Like if there are other users on the website will they also see this permanently whenever they visit the site? Allowing people to edit the html for other users. – DiamondKingx Dec 07 '21 at 10:47
  • @DiamondKingx This depends on where you are going to store the output. If you run this code to the server-side or have upload access rights to the server, then, overwriting the content of the file you just read, with the output of `$.html()` (last line), would update the view for all the users on their next request (supposing you use a statically-served site). For a dynamic site you will need to save the output to some storage (e.g. db) from which it was read and sent to each browser upon request. There are also push mechanisms that support auto-refresh of browsers content without page reload – Marinos An Dec 07 '21 at 10:53
0

Actually no, usually people use a library or a framework in order to connect front end with the back end and in your case is Node.js.

You can use reactjs, but if you thought it's complicated at this time you can use EJS in order to display data in your html, it's easy to install with npm.

npm install ejs

EL-Mehdi Loukach
  • 732
  • 2
  • 9
  • 28
  • but i recive date from html into node how i could write them into html – Chipnick Feb 03 '20 at 19:56
  • can you say more about EJS – Chipnick Feb 03 '20 at 19:56
  • EJS is a library you can install it from npm, briefly, you can pass your data from your node js back end like this : res.json({yourdata:yourdata}). In your html file you can use a for loop with ejs like this : <% if(data){ for(var i =0; i< data.length; i++) { %>
    <% data[i] %>
    <% } } %>
    – EL-Mehdi Loukach Feb 03 '20 at 21:01
  • you will find the exact information you re looking for in the link in the comment above – EL-Mehdi Loukach Feb 03 '20 at 21:02