What are the use cases of jsdom

Raynos picture Raynos · May 23, 2011 · Viewed 10k times · Source

After reading this Micro templates are dead article. I've become curious:

  1. Whether Using the DOM on the server results in cleaner more maintainable code then templating.
  2. Whether it's more efficient to use jsdom instead of a templating engine.
  3. How to factor jsdom into the View of a standard MVC setup.

And generally in what situations would it be better to use a server-side DOM abstraction, like jsdom rather then a templating engine, like EJS or jade.

The question is specific to node.js and other SSJS

Answer

Hacknightly picture Hacknightly · May 23, 2011

Well, I actually needed JSDom for a small project I built over the weekend in node.js. So, on my server, I had to accept a URL to fetch, grab all of the HTML from the given URL, parse it, and display images to the user so that the user could select a thumbnail from that URL. (Kind of like when you drop a link into the Facebook input box) So, I used a module called Request which allows me to fetch HTML on the server-side. However, when that HTML reached my program, I had no way to traverse it like you do with client-side javascript. Because there was no actual DOM, I couldn't say document.getElementById('someId'). Therefore, JSDom came in handy by giving me a "makeshift" DOM that allowed me to traverse the returned HTML. Now, even though I was still on the server side, JSDOM created a window object very similar to the window object in the browser, and created a DOM out of the returned HTML. Now, even on the server, I was able to get all images by calling window.$('img'). I could target and parse the elements like normal. So, this is just one problem where JSDom turned out to be the solution, but it worked amazingly well. Hope this helps some!