1

I'm trying to use NodeJS to modify an external HTML file (which is located in the same directory). In my index.js file I write:

fs.readFile('index.html', (err,html)=>{
  if(err){
     throw err;
  }

html.body.innerHTML += '<div id = "asdf"></div>';

});

As index.html is a valid document. But it doesn't look to be reading it properly, as I get as an error:

"TypeError: Cannot read property 'innerHTML' of undefined".

I guess that html is not getting anything as body.

How can I do changes in HTML using JavaScript?

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122

3 Answers3

8

Here is an example using node-html-parse

HTML file

<html>
   <body>
      <div id="fist">yolo</div>
   </body>
</html>

And the nodejs

const fs = require('fs');
const parse = require('node-html-parser').parse;

fs.readFile('index.html', 'utf8', (err,html)=>{
   if(err){
      throw err;
   }

   const root = parse(html);

   const body = root.querySelector('body');
   //body.set_content('<div id = "asdf"></div>');
   body.appendChild('<div id = "asdf"></div>');

   console.log(root.toString()); // This you can write back to file!
 });

There might be better solutions than node-html-parser, considering the amount of downloads. For example, htmlparser2 has much more downloads, but it also looks more complex :)

Jeanluca Scaljeri
  • 26,343
  • 56
  • 205
  • 333
  • I had to change the second argument of 'fs.readFile' to `utf8`, but it looks great. Thank you so much! Also, html parser looks to be helpful for more complex things to do. – F.J. Klaiber Aboitiz Oct 07 '19 at 09:01
1

In order to manipulate an html file the way you'd be able to in a browser, you'll first need to parse it.

Perhaps node-html-parser can be of use? (Or if a few milliseconds of parsing are not a concern and you want some more functionality, the JSDOM package is very popular too.)

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
Matt
  • 699
  • 5
  • 15
-1

innerHTML is a function provided after DOM parsing. Here you are using a string, so you can either use a DOM parser to create the structure or you can just use regex to isolate the part you want to replace and append the text.

html.replace("</body>",'<div id = "asdf"></div></body>');
Dhananjai Pai
  • 5,914
  • 1
  • 10
  • 25
  • That's right, but my main problem now is that I'm not getting the `HTML` document in the `html`variable. Now I'm getting `TypeError: html.replace is not a function`. – F.J. Klaiber Aboitiz Oct 07 '19 at 07:11
  • are you sure the path is right ? I mean, it is basic fileread, once you have the string in the callback, it should be easy. What is the error you are getting ? – Dhananjai Pai Oct 07 '19 at 07:17
  • 1
    In your case `readFile` returns a `Buffer`. Read the file as `fs.readFile('index.html', 'utf8', (err, html) => { ... })` and it will work. But doing this with RegExes is fragile, don't do it and use a parser! – Jeanluca Scaljeri Oct 07 '19 at 07:41