2

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");
2
  • 2
    for why its not defined in nodejs look here: stackoverflow.com/questions/32126003/… Commented Aug 4, 2016 at 8:37
  • Yeah I look into it. but it is pointing out the issue. Not telling how to achieve this Commented Aug 4, 2016 at 8:45

1 Answer 1

1

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

  }
});
Sign up to request clarification or add additional context in comments.

4 Comments

how to install jsdom
npm install node-jsdom
@Tuhin The OP asked a question which can be answered in multiple ways. One of them is "use jsdom". This does not warrant adding the tag to the question. So I've reverted your edit. It would have been okay if the OP had specifically asked a question about jsdom but that was not the case here.
Okay.. I will remove then

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.