简体   繁体   English

如何替换所有的HTML代码 <body> 用NodeJS标记?

[英]How to replace all html code of the <body> tag with NodeJS?

Based on: https://stackoverflow.com/a/14181136/3363138 I did the corresponded modifications: 基于: https : //stackoverflow.com/a/14181136/3363138我做了相应的修改:

var fs = require('fs')
var desired_code = '<div>Desired Code</div>'

fs.readFile(file.html, 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }

  //Here I need to load all the body tag content, but how?
  var result = data.replace(<body>html tags to be replaced</body>, desired_code);

  fs.writeFile(file.html, result, 'utf8', function (err) {
     if (err) return console.log(err);
  });
});

On this function I need to load all the body tag content, but how can I do it? 在此功能上,我需要加载所有正文标签内容,但是我该怎么做呢?

var result = data.replace(<body>html tags to be replaced</body>, desired_code);

If you want to change something in html code that is String, I see two options now : 如果您想更改html代码中的String,那么现在可以看到两个选项:

  • You write a Regex expression for that (easy, fast, but less clean and secure) ; 您为此编写了一个Regex表达式(简单,快速,但不太干净和安全);
  • You use a html parser like cheerio.js, change your node "body" and stringify (more complicated but more secure and clean). 您使用诸如cheerio.js之类的html解析器,更改节点的“ body”并进行字符串化(更复杂,但更安全更干净)。

For the first option, something like : data = data.replace(/<body>(.*)<\\/body>/, '<div>Hello world</div>'); 对于第一个选项,类似于: data = data.replace(/<body>(.*)<\\/body>/, '<div>Hello world</div>');

For the second option, something like : 对于第二个选项,类似:

parsed = cheerio.parse(data); parsed.find('body').html('<div>Hello world</div>'); data = cheerio.html();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM