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>")
3
  • You should share more details of your code. change HTML by Node.js are far too fewer information. Commented Feb 3, 2020 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. Commented Feb 3, 2020 at 18:37
  • when i try with DOM it say document didn't founded Commented Feb 3, 2020 at 20:00

2 Answers 2

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>
Sign up to request clarification or add additional context in comments.

2 Comments

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

4 Comments

but i recive date from html into node how i could write them into html
can you say more about EJS
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++) { %> <div> <% data[i] %> </div> <% } } %>
you will find the exact information you re looking for in the link in the comment above

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.