Sayan Sarkar Sayan Sarkar - 4 months ago 16
HTML Question

Create HTML file by using HTML DOM methods and write into that HTML file in nodejs

I am trying to write HTML file in nodejs. I need to create elements using all the DOM methods. I tried following, but throwing error

document is undefined
. Please suggest me what wrong I am doing and what is the right way to do this. Thanks

var fs = require('fs');

var myDiv= document.createElement("div");
myDiv.setAttribute("id","myDiv");'

var data = myDiv.outerHTML;

var writerStream = fs.createWriteStream('abcd.html');
writerStream.write(data,'UTF8');
writerStream.end();
writerStream.on('finish', function() { console.log("Write completed."); });
writerStream.on('error', function(err){ console.log(err.stack); });
console.log("Program Ended");

Answer

This issue is due to there is no window object available. Remember document object comes from window. When we write document, it is actually window.document. But nodejs does not provide the window object, as it runs on serverside.

So to do this you can use a module called jsdom. Go through jsdom here: https://www.npmjs.com/package/node-jsdom

Install jsdom and try something like:

var jsdom  = require('jsdom');
var fs     = require('fs');
var http = require("http");
http.createServer(function (request, response) {
     response.writeHead(200, {'Content-Type': 'text/plain'});
     response.end('Hello World\n'); 
}).listen(8081); 
console.log('Server running at http://127.0.0.1:8081/');

jsdom.env({
  html: 'http://127.0.0.1:8081/',
  src: [],
  done: function(errors, window) {

    var document = window.document;
    var myDiv= document.createElement("div");
    myDiv.setAttribute("id","myDiv");'

    var data = myDiv.outerHTML;

    var writerStream = fs.createWriteStream('abcd.html');
    writerStream.write(data,'UTF8');
    writerStream.end();
    writerStream.on('finish', function() {    console.log("Write completed."); });
    writerStream.on('error', function(err){   console.log(err.stack); }); 
    console.log("Program Ended");

  }
});