最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to change or edit Html in Node.js - Stack Overflow

programmeradmin0浏览0评论

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

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>")
Share Improve this question edited Feb 3, 2020 at 18:31 Chipnick asked Feb 3, 2020 at 17:35 ChipnickChipnick 431 gold badge1 silver badge6 bronze badges 3
  • You should share more details of your code. change HTML by Node.js are far too fewer information. – Nico Schuck 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. – David S. Commented Feb 3, 2020 at 18:37
  • when i try with DOM it say document didn't founded – Chipnick Commented Feb 3, 2020 at 20:00
Add a ment  | 

2 Answers 2

Reset to default 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>

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

发布评论

评论列表(0)

  1. 暂无评论