Node.js 创建可二次编辑的 HTML 文档并生成文件

Node.js 环境 中直接用浏览器的 document 对象会报错(Node 没有原生 DOM),所以需要用 jsdom 库模拟浏览器 DOM,实现你要的:

  1. document.implementation.createHTMLDocument 创建 HTML 文档
  2. 支持二次编辑(增删改元素、样式、文本)
  3. 生成真实可运行的 HTML 文件

一、核心步骤

  1. 安装 jsdom(Node 模拟 DOM 的标准库)
  2. createHTMLDocument 创建空白 HTML 文档
  3. 二次编辑 DOM(添加标题、内容、样式、脚本等)
  4. 导出完整 HTML 字符串并写入本地文件

二、完整可直接运行代码

1. 先初始化项目 + 安装依赖

打开终端,执行:

复制代码
# 初始化项目(一路回车)
npm init -y
# 安装 jsdom 核心依赖
npm install jsdom

2. 完整代码(create-edit-html.js)

复制代码
// 1. 引入 jsdom 库(Node 环境模拟浏览器 DOM)
const { JSDOM } = require('jsdom');
// 引入 Node 原生文件模块(用于写入 HTML 文件)
const fs = require('fs');
const path = require('path');

// 2. 创建 JSDOM 实例,获取 document 对象
const dom = new JSDOM('<!DOCTYPE html>');
const document = dom.window.document;

// ====================== 核心:创建 HTML 文档 ======================
// 完全使用你要求的语法:createHTMLDocument
const newDoc = document.implementation.createHTMLDocument('我的可编辑 HTML 文档');
console.log('✅ 初始 HTML 文档创建成功');

// ====================== 二次编辑 DOM(核心功能) ======================
// 1. 编辑标题
newDoc.title = '二次编辑后的标题';

// 2. 获取 body 元素,添加内容
const body = newDoc.body;
body.style.backgroundColor = '#f5f5f5'; // 编辑样式

// 3. 创建并添加标题元素
const h1 = newDoc.createElement('h1');
h1.textContent = 'Node.js 生成 · 支持二次编辑';
h1.style.color = '#2d8cf0';
body.appendChild(h1);

// 4. 创建并添加段落
const p = newDoc.createElement('p');
p.textContent = '这个 HTML 文档完全由 Node 生成,支持任意 DOM 操作';
p.style.fontSize = '16px';
body.appendChild(p);

// 5. 动态添加脚本(可编辑任何内容)
const script = newDoc.createElement('script');
script.textContent = `console.log('这是 Node 生成的 HTML 脚本');alert('打开页面成功!');`;
body.appendChild(script);

// ====================== 生成真实 HTML 文件 ======================
// 1. 将 DOM 文档转为完整 HTML 字符串(包含 doctype、html、head、body)
const finalHtml = `<!DOCTYPE html>${newDoc.documentElement.outerHTML}`;

// 2. 定义输出文件路径
const outputPath = path.join(__dirname, 'edited-html.html');

// 3. 写入本地文件
fs.writeFile(outputPath, finalHtml, 'utf8', (err) => {
  if (err) {
    console.error('❌ 写入文件失败:', err);
    return;
  }
  console.log('✅ HTML 文件生成成功!路径:', outputPath);
  console.log('📝 支持二次编辑:可继续修改 newDoc 对象后重新生成');
});

三、关键功能说明

1. 为什么用 jsdom

  • Node.js 没有浏览器的 documentwindow 原生对象
  • jsdom 是官方推荐的 DOM 模拟库,完美支持 document.implementation.createHTMLDocument

2. 完全使用你要求的语法

复制代码
// 就是你要的这行代码,无修改
const newDoc = document.implementation.createHTMLDocument('新文档');

3. 真正的「二次编辑」

newDoc标准 DOM 文档对象,支持所有浏览器 DOM 操作:

复制代码
// 二次编辑示例(直接加在代码里即可)
// 新增按钮
const btn = newDoc.createElement('button');
btn.textContent = '点击我';
btn.onclick = function() { alert('二次编辑的按钮'); };
newDoc.body.appendChild(btn);

// 修改已有元素
h1.textContent = '修改后的标题';
// 删除元素
// newDoc.body.removeChild(p);

4. 生成「真正的 HTML 文件」

  • 最终输出的 edited-html.html标准可直接打开的 HTML 文件

  • 双击就能在浏览器运行,包含完整结构:

    复制代码
    <!DOCTYPE html>
    <html>
      <head><title>二次编辑后的标题</title></head>
      <body style="background-color:#f5f5f5">
        <h1 style="color:#2d8cf0">Node.js 生成 · 支持二次编辑</h1>
        ...
      </body>
    </html>

四、运行代码

终端执行:

复制代码
node create-edit-html.js

运行后会在当前文件夹生成 edited-html.html,双击打开即可使用。

五、扩展:多次编辑 + 多次生成

如果需要多次修改、多次生成文件,直接封装成函数:

复制代码
// 封装:生成文件函数
function saveHtml(doc, filename) {
  const html = `<!DOCTYPE html>${doc.documentElement.outerHTML}`;
  fs.writeFileSync(path.join(__dirname, filename), html, 'utf8');
}

// 第一次编辑 + 生成
saveHtml(newDoc, 'v1.html');

// 二次编辑
const div = newDoc.createElement('div');
div.textContent = '第二次编辑的内容';
newDoc.body.appendChild(div);

// 重新生成
saveHtml(newDoc, 'v2.html');

总结

  1. Node 环境必须用 jsdom 模拟 DOM,才能使用 createHTMLDocument
  2. newDoc 是标准 DOM 对象,支持所有浏览器 DOM 二次编辑操作
  3. 最终通过 fs 模块写入文件,生成可直接运行的真实 HTML
  4. 代码可直接复制运行,无其他依赖,轻量稳定
相关推荐
Cat_Rocky2 小时前
创建LNMRP后端技术栈
java·开发语言
牛马1112 小时前
Flutter BoxDecoration border 完整用法
开发语言·前端·javascript
biter down2 小时前
STL list
开发语言·c++
xyq20242 小时前
R 绘图 - 函数曲线图
开发语言
Lyyaoo.2 小时前
【JAVA基础面经】进程间的通信方式
java·开发语言·python
We་ct2 小时前
LeetCode 149. 直线上最多的点数:题解深度剖析
前端·javascript·算法·leetcode·typescript
小此方2 小时前
Re:思考·重建·记录 现代C++ C++11篇 (三) 深度解构:可变参数模板、类功能演进与 STL 的新版图
开发语言·c++·stl·c++11·现代c++
小坏讲微服务2 小时前
Claude Code 终极实战指南:从终端 Agent 到 AI+Java 开发
java·开发语言·人工智能
爱学习的小囧2 小时前
ESXi 8.0 vSwitch与dvSwitch(分布式交换机)核心区别
服务器·开发语言·分布式·php·虚拟化