Comprehensive Guide to jsdom Unlock the Power of JavaScript in Node.js

Introduction to jsdom

jsdom is a popular JavaScript implementation of the WHATWG DOM and HTML standards, primarily designed to be used with Node.js.
This library allows you to manipulate DOM from the server side. It is extensively used for testing, web scraping,
and in server-rendered applications.

Basic Usage

Let’s start with a simple example of setting up jsdom:

  const jsdom = require('jsdom');
  const { JSDOM } = jsdom;

  const dom = new JSDOM(`

Hello world

`); console.log(dom.window.document.querySelector("p").textContent); // "Hello world"

Manipulating the DOM

You can create elements and manipulate them as you would in a browser environment:

  const { window } = new JSDOM(`
`); const { document } = window; const newElem = document.createElement("p"); newElem.textContent = "This is a new paragraph"; document.getElementById("app").appendChild(newElem); console.log(document.body.innerHTML); //

This is a new paragraph

Using External Resources

jsdom can also load and parse HTML from external resources:

  JSDOM.fromURL("https://example.com").then(dom => {
    console.log(dom.window.document.title);
  });

Interacting with Forms

Here’s how to interact with a form element in jsdom:

  const dom = new JSDOM(`
`); const input = dom.window.document.querySelector("input"); input.value = "jsdom_user"; console.log(input.value); // "jsdom_user"

Event Handling

Event handling in jsdom is very similar to how you do it in a browser:

  const dom = new JSDOM(``);
  const button = dom.window.document.querySelector("button");

  button.addEventListener("click", () => {
    console.log("Button was clicked!");
  });

  const clickEvent = new dom.window.MouseEvent("click");
  button.dispatchEvent(clickEvent); // "Button was clicked!" gets printed

Handling Scripts

jsdom can execute scripts in a controlled environment:

  const dom = new JSDOM(`

Hello World

`, { runScripts: "dangerously", resources: "usable" }); dom.window.eval(`document.querySelector('p').textContent = 'Hello jsdom'`); console.log(dom.window.document.querySelector("p").textContent); // "Hello jsdom"

Complete Application Example

Let’s build a mini server-side application using some of the APIs we’ve covered:

  const jsdom = require('jsdom');
  const { JSDOM } = jsdom;
  const http = require('http');

  const server = http.createServer((req, res) => {
    JSDOM.fromURL("https://example.com").then(dom => {
      const document = dom.window.document;
      const title = document.querySelector("title").textContent;
      const newElem = document.createElement("p");
      newElem.textContent = "Fetched title is: " + title;
      document.body.appendChild(newElem);
      
      res.writeHead(200, {'Content-Type': 'text/html'});
      res.write(dom.serialize());
      res.end();
    });
  });

  server.listen(3000, () => {
    console.log("Server listening on port 3000");
  });

In the above example, a small HTTP server fetches the content of an external page, modifies it, and serves it to clients.

Hash: 338410d1cfb176ccc55117a9b003099ce83bf45f8364176f3005f061e8d4e2b9

Leave a Reply

Your email address will not be published. Required fields are marked *