0

Based on: https://stackoverflow.com/a/14181136/3363138 I did the corresponded modifications:

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);
Community
  • 1
  • 1
Carlos
  • 131
  • 3
  • 13

1 Answers1

2

If you want to change something in html code that is String, I see two options now :

  • You write a Regex expression for that (easy, fast, but less clean and secure) ;
  • You use a html parser like cheerio.js, change your node "body" and stringify (more complicated but more secure and clean).

For the first option, something like : 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();

Chubaka
  • 21
  • 2