Node.js,如何在浏览器中查看jsdom

问题描述

如何在浏览器中查看html?在localhost:3000上没有任何显示

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`<!DOCTYPE html><body><p id="main">My First JSDOM!</p></body>`,{
    url: "http://localhost:3000/",contentType: "text/html",pretendToBeVisual: true,}
);

解决方法

从我收集到的评论中,您想在节点中的JSDOM中操作DOM,然后(也许)编写一个html文件(或在响应中返回它)

为此,请使用serialize()

https://github.com/jsdom/jsdom#serializing-the-document-with-serialize

以您的示例为例:

const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const dom = new JSDOM(`<!DOCTYPE html><body><p id="main">My First JSDOM!</p></body>`,{
    url: "http://localhost:3000/",contentType: "text/html",pretendToBeVisual: true,}
);

console.log(dom.serialize());

JSm将为您提供所有HTML的字符串。 然后,您可以使用Express.js创建可以返回该HTML的服务器,也可以使用该字符串将HTML文件写入磁盘。

const express = require('express');
const jsdom = require("jsdom");

const { JSDOM } = jsdom;
const dom = new JSDOM(`<!DOCTYPE html><body><p id="main">My First JSDOM!</p></body>`,}
);

const app = express();

app.get('/',(req,res) => {
  res.send(dom.serialize());
});

app.listen(8080,() => {
  console.log('Example app listening at http://localhost:8080');
});